Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

Swift Rest API call example using Codable

I am following a tutorial on REST API calls with Swift and Codable. I cannot compile the following although I was careful when I typed all of it. Can anyone tell me what's wrong? Also, can anyone point me to a better tutorial? The error is:

Catch block is unreachable

and also

cannot find json in scope

import UIKit
import Foundation

struct Example: Codable {
    let userId: Int
    let id: Int
    let title: String
    let completed: Bool
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    


    func getJson(completion: @escaping (Example)-> ()) {
        let urlString = "https://jsonplaceholder.typicode.com/todos/1"
        if let url = URL(string: urlString) {
            URLSession.shared.dataTask(with: url) {data, res, err in
                if let data = data {
                    
                    let decoder = JSONDecoder()
                    do {
                        let json: Example = try! decoder.decode(Example.self, from: data)
                        completion(json)
                    }catch let error {
                        print(error.localizedDescription)
                    }
                }
            }.resume()
        }
    }

    getJson() { (json) in
        print(json.id)
    }


}
question from:https://stackoverflow.com/questions/65876500/swift-rest-api-call-example-using-codable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of "do catch", you can use "guard let"

func getJson(completion: @escaping (Example)-> ()) {
    let urlString = "https://jsonplaceholder.typicode.com/todos/1"
    if let url = URL(string: urlString) {
    URLSession.shared.dataTask(with: url) {data, res, err in
        guard let data = data else {return print("error with data")}
        let decoder = JSONDecoder()
        guard let json: Example = try? decoder.decode(Example.self, from: data) else {return print("error with json")}
        completion(json)
      }.resume()
    }
}

This does NOT handle errors, so my solution is just to an answer to your question, not a general solution for every similar cases.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...