在 Json 中从服务器接收数据 Swift

Receive data from server in Json for Swift

我使用此代码将用户登录到服务器,我工作正常但我在获取令牌时遇到问题

在这里,我收到带有 String(最后一个 IF)

的登录数据
   var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = body.percentEscaped().data(using: .utf8)

    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if let error = error {
            print("error: \(error)")
        } else {
            if let response = response as? HTTPURLResponse {
                print("statusCode: \(response.statusCode)")
            }
            if let data = data, let dataString = String(data: data, encoding: .utf8) {
                print("data: \(dataString)")
            }
        }
    }

有什么方法可以将其转换为 Json?或者总的来说,在登录过程中,我最好将数据作为 Json 或 String?

谢谢

从Swift4开始,Swift有自己的JSONEncoder and Decoder

Here 是苹果的参考页。看看这个,弄清楚你需要什么。

这是我提供的非常简单的示例代码。

// YourTokenModel.swift
struct YourTokenModel: Decodable {
    var token: String
}

// YourTokenController.swift
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = body.percentEscaped().data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    if let error = error {
        print("There is a error while communication")
        return
    }

    guard let data = data else {
        print("No data comes out. Returning...")
        return
    }

    do {
        let decodedData = try JSONDecoder().decode(YourTokenModel.self, from: data)
        print(decodedData.token)
        // DO WHATEVER YOU WANT! //
    } catch let error {
        print("There is a error while decoding your JSON Model")
        print(error)
    }
}

task.resume()