【问题标题】:Swift: JSON file from URL instead of localSwift:来自 URL 而不是本地的 JSON 文件
【发布时间】:2015-12-09 12:37:30
【问题描述】:

现在我有这个:

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

【问题讨论】:

  • 到目前为止您尝试了什么?任何代码示例

标签: json xcode swift


【解决方案1】:

您需要阅读一些苹果文档: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()
}

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 2012-06-18
    • 2012-11-01
    • 2010-12-03
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 2012-11-22
    相关资源
    最近更新 更多