json - Swift:来自 URL 而不是本地的 JSON 文件

标签 json xcode swift

现在我有这个:

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 接收文件,而不是将其放在我的应用程序中。

最佳答案

您需要阅读一些苹果文档:NSURLConnectionNSURLSession

这里有一个快速解决方案,可以帮助您实现这一目标。

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/

相关文章:

swift - 如何在 NSManagedObject Swift 扩展中创建托管对象子类的实例?

javascript - JSON.parse() 无法解析带有 HTML 的字符串

python - 将字典解析为 csv 文件

swift - Swift 中等效的列表框

ios - 如何修复 Swift 中的 "ActionSheet of UIAlertController has the conflict constraint"错误

iphone - 如何根据给定的坐标移动 UIImage

swift - 如何快速将数据从iphone发送到watchkit

java - 如何使用 Jackson 重命名 JSON 序列化中的根键

php - json 解析失败 - cocoa 错误 3840 和字符 0 周围的无效值

xcode - 自动转换为 ARC 时是否可以跳过某些文件?