现在我有这个:
let path : String = NSBundle.mainBundle().pathForResource("jsonFile", ofType: "json") as String!
let jsonData = NSData(contentsOfFile: path) as NSData!
let readableJSON = JSON(data :jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil)
但我想从 URL 接收文件,而不是将其放在我的应用程序中。
最佳答案
您需要阅读一些苹果文档:NSURLConnection和 NSURLSession
这里有一个快速解决方案,可以帮助您实现这一目标。
func fetchDetailsFromServer() {
let urlPath = "Server URL to Fetch JSON"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
println("Task completed")
if(error != nil) {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary {
if(err != nil) {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
// Use your jsonResult appropriately here
}
})
// The task is just an object with all these properties set
// In order to actually make the web request, we need to "resume"
task.resume()
}
关于json - Swift:来自 URL 而不是本地的 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32549067/