Swift Rest API 使用 Codable 的调用示例

Swift Rest API call example using Codable

我正在学习使用 Swift 和 Codable 进行 REST API 调用的教程。尽管我在输入所有内容时都很小心,但我无法编译以下内容。谁能告诉我怎么了?另外,任何人都可以指出我更好的教程吗?错误是:

Catch block is unreachable

还有

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)
    }


}

你可以用“guard let”代替“do catch”

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()
    }
}

不会处理错误,所以我的解决方案只是对您问题的回答,而不是针对所有类似情况的通用解决方案。

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

 
struct APIRequest {
    
    var resourceURL: URL
    let urlString = "https://jsonplaceholder.typicode.com/todos/1"
   
    init() {
        resourceURL = URL(string: urlString)!
    }
    
    //create method to get decode the json
    func requestAPIInfo(completion: @escaping(Result<Example, Error>) -> Void) {
        
        let dataTask = URLSession.shared.dataTask(with: resourceURL) { (data, response, error) in
            
            guard error == nil else {
                print (error!.localizedDescription)
                print ("stuck in data task")
                return
            }
            
            let decoder = JSONDecoder()
            
            do {
                let jsonData = try decoder.decode(Example.self, from: data!)
                completion(.success(jsonData))
            }
            catch {
                print ("an error in catch")
                print (error)
            }
            
            
        
        }
        dataTask.resume()
    }
}


class ViewController: UIViewController {

    let apiRequest = APIRequest()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        apiRequest.requestAPIInfo { (apiResult) in
            print (apiResult)
        }
    }
}