簡體   English   中英

swift 5 ios:如何從 session.dataTask 完成處理程序中獲取數據

[英]swift 5 ios : how do I get data out of a session.dataTask completion handler

我有下面的代碼,它不完整,例如。

    func getUserData() {
        var user: UserData // creates an empty userdata object
        // setup for session.dataTask below, skipping since this isn’t my question
        let task = session.dataTask(with: url) {(data, response, error) in
            …
            // process data here
            let json = JSONSERializable.jsonobject…
            // How can I get the json variable out into the function?
            // Because I can do something like:
            let id = json[“id”] as? String ?? “”
            let name = json[“name”] as? String ?? “”
            // And I would want to do something like:
            userdata.id = id
            userData.name = name
        }
        task.resume()
    }

但上面的用戶數據。 陳述是錯誤的,我似乎無法理解這個概念。

我有一個應用程序向安靜的 api 發出大量請求,我得到 json 數據有效負載以在應用程序中使用。 所以我有很多這類數據調用,並且想創建一個 class 的方法來訪問遠程數據庫的各個方面。

任何幫助將不勝感激。

這段代碼對我有用:

    func loadJson(fromURLString urlString: String,
                      completion: @escaping (Result<Data, Error>) -> Void) {
    if let url = URL(string: urlString) {
        let urlSession = URLSession(configuration: .default).dataTask(with: url) { (data, response, error) in
            if let error = error {
                completion(.failure(error))
            }
            
            if let data = data {
                completion(.success(data))
            }
        }
        urlSession.resume()
    }
}

並使用:

 loadJson(fromURLString: urlString) { (result) in
    switch result {
    case .success(let data):
        // Parse your Json: I call a function Parse that does it
        //if let decodedJson = GetJson.parse(jsonData: data) {
            //DispatchQueue.main.async {
                //Use your decodedJson
                //print(decodedJson.id)
                //print(decodedJson.name)
            //}
                
       }
    case .failure(let error):
        print(error)         
    }
}

假設您的用戶 object 符合 Codable 例如:

struct User: Codable {
    let id: String
    let name: String

    enum CodingKeys: String, CodingKey {
    
        case id = "user_id" //If the parameters of your json object you receive are named differently than the variable name above
        case name
    }
}

然后在您的getUserData() function 中,您可以執行以下操作:

func getUserData(_ completion: @escaping(User?, Error?) -> Void) {
    let url = URL(string: "example.com")!

    let session = URLSession(configuration: .default)


    session.dataTask(with: url) {(data, response, error) in
        if let error = error {
            print("error is \(error.localizedDescription)")
            completion(nil, error)
            return
        }
    
        guard let data = data else {
        //THERE IS NO DATA RETURNED, Might want to handle this case
            return
        }
    
        do {
            let user = try JSONDecoder().decode(User.self, from: data) //Creates a User Object if your JSON data matches the structure of your class
            completion(user, nil)
        } catch (let decodingError) {
            completion(nil, decodingError)
        }
    }.resume()
}

然后根據實際使用情況,您可以執行以下操作:

func loadDataAndUpdateUI() {
    getUserData { (user, error) in
        if let user = user {
            userIdLabel.text = user.id
        } else if let error = error {
            //Handle or show this error somehow
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM