【问题标题】:I need to fetch a JSON in a URL我需要在 URL 中获取 JSON
【发布时间】:2016-09-13 07:30:54
【问题描述】:

我读过这篇关于 URL 加载系统的文章:

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html#//apple_ref/doc/uid/10000165i

无法弄清楚使用什么类以及如何使用它。

errorSreenshot

【问题讨论】:

标签: ios json swift


【解决方案1】:

我建议使用像Alamofire这样的第三方框架。原生的Swift网络相当复杂,特别是对于初学者来说,因为Swift是类型安全的语言,JSON对象可以有嵌套等,只有在实际获取后才能看到的对象。

好消息是 Alamofire 可以很容易地与 CocoaPods 一起安装,并且它正在积极开发中。这是一个使用 Alamofire 的 Swift 3 4.0 版本从名为 yourUrl 的 url 获取 JSON 对象的请求示例:

Alamofire.request("https://yourUrl").responseJSON { response in
  print(response.request)  // original URL request
  print(response.response) // HTTP URL response
  print(response.data)     // server data
  print(response.result)   // result of response serialization

  if let json = response.result.value {
    print("JSON: \(json)")
    // do something with json here
  }
}

然后,您可以使用另一个第三方框架(例如 SwiftyJSON)来解析您检索到的 JSON - 特别是在它具有复杂结构的情况下。但遗憾的是,Swift 3 没有更新,所以我想我们必须等待,看看结果如何。

编辑: SwiftyJSON 有一个非官方的 Swift 3 分支,可以与 cocoapods 一起安装(它适用于 iOS10/Swift 3):

pod 'SwiftyJSON', git: 'https://github.com/BaiduHiDeviOS/SwiftyJSON.git', branch: 'swift3'

【讨论】:

  • 谢谢!如何查看我是否真的安装了 cocoapods?
  • @MatteoVilla pod --version 在您的终端中;查看他们的官方guides 了解更多信息
  • 我按照步骤通过 Cocoapods 安装 Alamofire。但是当我尝试使用 xcode 构建项目时,我遇到了几个问题。我在问题中添加了屏幕截图
  • 安装 CocoaPods 与 原生 Swift 网络一样相当复杂,尤其是对于初学者 ;-)
  • 好的,我知道原因了...我必须安装 swift 3.0 和 xcode 8 才能使用 Alamofire 4.0
【解决方案2】:

使用以下函数加载 URL。

fun loadURL()->void{
 let defaultSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
    var dataTask: NSURLSessionDataTask?
    let url = NSURL(string: "URL TO LOAD")//Add url string here
    dataTask = defaultSession.dataTaskWithURL(url!) {
        data, response, error in
        dispatch_async(dispatch_get_main_queue()) {
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
        }
        if let error = error {
            print(error.localizedDescription)
        } else if let httpResponse = response as? NSHTTPURLResponse {
            if httpResponse.statusCode == 200 {
                print(data);
                //Process data here..
            }
        }
    }
    dataTask?.resume()
}

您可以使用 NSJSonSerialization 类中的 build 将 NSdata 转换为 NSDictionary,然后解析 Dictionary 以提取值。您的解析逻辑将被添加 //Process data here.. 代替上面代码库中的此注释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 2012-12-29
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多