美文网首页
Swift 网络请求与数据解析(JSON与模型互转)

Swift 网络请求与数据解析(JSON与模型互转)

作者: IMKel | 来源:发表于2024-08-01 09:57 被阅读0次
    // 注意:解析时json与模型属性个数可以不匹配,但类型必须匹配
    struct Respone: Codable {
        let code: Int?
        let message: String?
        let data: TokenData?
    }
    
    struct TokenData: Codable {
        let accessToken: String?
        let type: String?
        let expiresAt: Int?
        
        // 注意:json的key和模型属性不同时,可以使用映射
        enum CodingKeys: String, CodingKey {
            case accessToken = "access_token"
            case type
            case expiresAt = "expires_at"
        }
    }
    
    // MARK: - Net
    private func loadData() {
        // 注意:swift要求集合包含不同类型的值时要显式指定参数类型。
        let parameters: [String : Any] = ["brand":"Apple", "channel":1, "device_id":"123431472xvwerbxcvbvxc", "oaid":"", "os":"17.5.2", "device_mode":"iPhone X"]
        // Foundation 对象转 json data
        let jsonData = try? JSONSerialization.data(withJSONObject: parameters)
        
        let url = URL(string: "https://xxx.xxx.com/api/auth/login/guest")!
        let sessionConfig = URLSessionConfiguration.default
        let session = URLSession(configuration: sessionConfig);
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        request.timeoutInterval = 5
        let task = session.dataTask(with: request) { data, response, error in
            if let error = error {
                print("出错了")
                return
            }
            
            guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
                print("请求出错了")
                return
            }
            if let mimeType = httpResponse.mimeType, mimeType == "application/json" {
                print("响应json类型")
                if let data = data {
                    print("data = \(String(describing: String(data: data, encoding:.utf8)))")
                    let decoder = JSONDecoder()
                    // jsonData 转 模型
                    if let resp = try? decoder.decode(Respone.self, from: data) {
                        print("resp.code = \(String(describing: resp.code))")
                        print("resp.message = \(String(describing: resp.message))")
                        print("resp.accessToken = \(String(describing: resp.data?.accessToken))")
                        print("resp.type = \(String(describing: resp.data?.type))")
                        print("resp.expiresAt = \(String(describing: resp.data?.expiresAt))")
                    }
                    // 或 jsonData 转 Foundation 对象(即基础数据类型Dictionary, Array等,非自定义类)
                    let jsonObj = try? JSONSerialization.jsonObject(with: data)
                    print("jsonObj = \(String(describing: jsonObj))")
                    if let dict = jsonObj as? Dictionary<String, Any?> {
                        print("code = \(String(describing: dict["code"]))")
                    }
                } else {
                    print("data 无数据")
                }
            } else {
                print("响应其他类型")
            }
        }
        task.resume()
    }
    
    private func loadData1() {
        let url = URL(string: "https://whatsdual.tools-global.com/api/auth/login/guest")!
        let sessionConfig = URLSessionConfiguration.default
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                print("出错了")
                return
            }
            
            guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
                print("请求出错了")
                return
            }
            if let mimeType = httpResponse.mimeType, mimeType == "application/json" {
                print("响应json类型")
                if let data = data {
                    print("data = \(String(describing: String(data: data, encoding:.utf8)))")
                    let decoder = JSONDecoder()
                    if let resp = try? decoder.decode(Respone.self, from: data) {
                        print("resp.code = \(String(describing: resp.code))")
                        print("resp.message = \(String(describing: resp.message))")
                        print("resp.data = \(String(describing: resp.data))")
                    }
                } else {
                    print("data 无数据")
                }
            } else {
                print("响应其他类型")
            }
    
        }
        task.resume()
    }
    

    相关文章

      网友评论

          本文标题:Swift 网络请求与数据解析(JSON与模型互转)

          本文链接:https://www.haomeiwen.com/subject/cfvnhjtx.html