使用 Codable 的 Swift Rest API 调用示例

标签 swift 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)
    }


}

最佳答案

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

关于使用 Codable 的 Swift Rest API 调用示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65876500/

相关文章:

class - 在 Swift 中实例化类时将值传递给要使用的类

ios - Swift 将 UNIX 时间转换为日期和时间

ios - 如何正确使用 Codable、CoreData 和 NSSet 关系?

ios - 在swift 4中使用codable解析嵌套数组

ios - 无法在 Swift 中访问可编码的结构值

ios - 如何在 CodingKeys 枚举(可编码协议(protocol))中使用通用值

Swift 4 解码简单的根级 json 值

swift - 在 SwiftUI 中延迟转换

ios - iOS 上的自定义模板系统

从命令行快速主运行/构建