【问题标题】:How to return JSON data from Swift URLSession [duplicate]如何从 Swift URLSession 返回 JSON 数据 [重复]
【发布时间】:2021-06-26 21:15:27
【问题描述】:

我正在尝试从 api 调用返回 json 数据。我能够成功访问 json 数据,但我正在努力寻找一种方法/最佳方法来返回它以便在我的应用程序中访问。感谢您的任何想法!

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // make the api call and obtain data
        let data = self.loadData()
        print("inside viewDidLoad", data) // prints 'inside viewDidLoad emptyString'
    }
    
    func loadData() -> String {
        var circData = "emptyString"
        let session = URLSession.shared
        let url = URL(string: "https://us-east-1.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/cirdata-khyvx/service/cirData/incoming_webhook/cirlAPI")!
        let task = session.dataTask(with: url, completionHandler: { data, response, error in
            if let json = try? JSONSerialization.jsonObject(with: data!, options: []) {
//                print("json: ", json) // prints the whole json file, verifying the connection works. Some 300kb of data.
//                print("json file type: ", type(of: json)) // prints '__NSArrayI'
                
                let jsonString = "\(json)"
                circData = jsonString
//                print("circData", circData) // prints the whole json file, verifying that the json string has been assigned to 'circData'
            }
        })
        task.resume()
//        print("after: ", circData) // prints 'after: emptyString'. It's as if the reassignment didn't take place.
        return circData
    }
}

【问题讨论】:

  • 运行搜索。类似的问题几乎每天都会被问到。

标签: json swift urlsession


【解决方案1】:

您不能同步返回值,因为获取 json 数据的 api 调用是异步的。您需要改用完成处理程序。

您可以在代码中的不同位置放置断点,以了解流程是如何执行的。

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.loadData(completion: { [weak self] (result, error) in
            if let error = error {
                print(error.localizedDescription)
            }
            if let result = result {
                print(result)
            }
        })
    }
    
    func loadData(completion: @escaping (_ data: Any?, _ error: Error?) -> Void) {
        let url = URL(string: "https://us-east-1.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/cirdata-khyvx/service/cirData/incoming_webhook/cirlAPI")!
        let task = URLSession.shared.dataTask(with: url, completionHandler: { data, response, error in
            if let error = error {
                completion(nil, error)
                return
            }
            do {
                if let data = data {
                    let json = try JSONSerialization.jsonObject(with: data, options: [.allowFragments])
                    completion(json, nil)
                } else {
                    completion(nil, nil)
                }
            } catch {
                completion(nil, error)
            }
        })
        task.resume()
    }
}

【讨论】:

  • 这个问题已经被问及回答了很多次了。
猜你喜欢
  • 2017-08-20
  • 1970-01-01
  • 1970-01-01
  • 2018-05-24
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 2021-04-18
相关资源
最近更新 更多