ios - 快速返回值 URLSession.shared.dataTask

标签 ios swift swift4

<分区>

我刚开始在 Swift 中编码,我有以下解析 JSON 的代码

func parse (latitude: Double, longtitude: Double){


    let jsonUrlString = "https://api.darksky.net/forecast/apiKey/\(latitude),\(longtitude)"

    guard let url = URL(string: jsonUrlString) else{
        return
    }

    var information: forecast?
    URLSession.shared.dataTask(with: url) { (data, res, err) in

        guard let data = data else { 
              return
        }

        do {
            let json = try JSONDecoder().decode(forecast.self, from: data)
            self.info = json

        } catch {
            print("didnt work")
        }

    }.resume()

    processJson(info)
}

我的问题是我想将存储在 JSON 中的数据传递给要使用 processJson 函数处理的类中的变量,但由于 dataTask 函数不返回任何值,并且 JSON 变量是本地存储的 我无法在类外处理信息变量(它总是返回 nil)。我想知道这个问题的解决方案是什么?我在使用 weather.getCoordinate() 时遇到了同样的问题。

最佳答案

您可以使用完成 block 来返回值。添加完成 block 你的功能是这样的

func parse (latitude: Double, longtitude: Double, completion: @escaping ((AnyObject) -> Void)){
    let jsonUrlString = "https://api.darksky.net/forecast/apiKey/\(latitude),\(longtitude)"

    guard let url = URL(string: jsonUrlString) else{
        return
    }

    var information: forecast?
    URLSession.shared.dataTask(with: url) { (data, res, err) in

        guard let data = data else { 
              return
        }

        do {
            let json = try JSONDecoder().decode(forecast.self, from: data)
            self.info = json
            completion(info)
        } catch {
            print("didnt work")
        }

    }.resume()

当你调用这个函数时,它会返回你的信息

parse( lat, long, {info in processJson(info) })

关于ios - 快速返回值 URLSession.shared.dataTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46210879/

上一篇:ios - 在没有电缆且不使用 TestFlight 的设备上运行 ipa?

下一篇:ios - postman 响应正常,但在 Swift 3 上的 Alamofire 返回失败

相关文章:

iphone - 按下按钮时以动画方式显示 View

swift - CIAdditionCompositing 段错误

swift - 让我们输入一个 for in 循环

ios - SceneKit SCNNode 跟随触摸移动

ios - pod 框架内的 Google map

iOS UIWebView 在 "WebThread"中崩溃

ios - 遍历 Swift 应用程序中的自定义 Parse 列

ios - LoadVIew() 中的 UIVisualEffectView

ios - 未从 firebase 添加 TableView 事件

iOS Charts(danielgindi) - 如何在每次迭代中更新图表数据?