gpt4 book ai didi

php - swift 5错误: “Expected to decode Dictionary but found an array instead.”

转载 作者:行者123 更新时间:2023-12-03 08:42:14 29 4
gpt4 key购买 nike

我是Swift编程的新手,我正在研究在网上找到的登录和注册表xcode示例。
它说,它适用于各种后端。所以我将其更改为与我的login.php文件一起使用。但我只是到目前为止...

func handleResponse(for request: URLRequest,
completion: @escaping (Result<[User], Error>) -> Void) {

let session = URLSession.shared

let task = session.dataTask(with: request) { (data, response, error) in

DispatchQueue.main.async {

guard let unwrappedResponse = response as? HTTPURLResponse else {
completion(.failure(NetworkingError.badResponse))
return
}

print(unwrappedResponse.statusCode)

switch unwrappedResponse.statusCode {

case 200 ..< 300:
print("success")

default:
print("failure")
}

if let unwrappedError = error {
completion(.failure(unwrappedError))
return
}

if let unwrappedData = data {

do {
let json = try JSONSerialization.jsonObject(with: unwrappedData, options: [])
print(json)
if let users = try? JSONDecoder().decode([User].self, from: unwrappedData) {
completion(.success(users))
} else {
let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: unwrappedData)
completion(.failure(errorResponse))
}

} catch {
completion(.failure(error))
}
}
}
}

task.resume()
}

我有这个请求功能。
func request(endpoint: String,
loginObject: Login,
completion: @escaping (Result<User, Error>) -> Void) {

guard let url = URL(string: baseUrl + endpoint) else {
completion(.failure(NetworkingError.badUrl))
return
}

var request = URLRequest(url: url)

do {
let loginData = try JSONEncoder().encode(loginObject)
request.httpBody = loginData
print(loginObject)
} catch {
completion(.failure(NetworkingError.badEncoding))
}

request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

handleResponse(for: request, completion: completion)
}

然后得到这个错误
typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

所以我在网上搜索,主要是在这里,出了什么问题。我测试了代码,找出了错误的出处,我发现了,我应该将代码更改为...
        if let unwrappedData = data {

do {
let json = try JSONSerialization.jsonObject(with: unwrappedData, options: [])
print(json)
if let users = try? JSONDecoder().decode([User].self, from: unwrappedData) {
completion(.success(users))
} else {
let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: unwrappedData)
completion(.failure(errorResponse))
}

} catch {
completion(.failure(error))
}
}

所以我认为这是解决我的问题的正确方法。但不幸的是,更改后我又遇到了另一个错误...
Member 'success' in 'Result<User, Error>' produces result of type 'Result<Success, Failure>', but context expects 'Result<User, Error>'

而且我什至无法构建和运行代码。有谁能够帮助我?
如有必要,我将我的login.php从数组更改为字典。

这是完工关闭吗?
enum MyResult<T, E: Error> {

case success(T)
case failure(E) }



func handleResponse(for request: URLRequest,
completion: @escaping (Result<User, Error>) -> Void) {
... }


enum NetworkingError: Error {
case badUrl
case badResponse
case badEncoding }

ErrorResponse.swift
import Foundation

struct ErrorResponse: Decodable, LocalizedError {
let reason: String

var errorDescription: String? { return reason } }

Login.swift
import Foundation

struct Login: Encodable {
let username: String
let password: String }

User.swift
import Foundation

struct User: Decodable {
let user_id: Int
let username: String
let password: String
let firstname: String
let surname: String
let activated: Int
let reg_time: String
}

打印(JSON)...
({
activated = 1;
firstname = Thomas;
password = Maggie;
"reg_time" = "0000-00-00 00:00:00";
surname = Ghost;
"user_id" = 2;
username = "testuser";
})

现在我几乎要重新营业了。我发现我在mysql中的user_id是int(3),但是swift 5并没有将它当作它。当我取出let user_id:int时,我终于摆脱了最后一条错误消息。但是现在我可以通过单击任何按钮以及任何用户名和密码登录,无论它是对还是错。

最佳答案

我相信问题在于完成结帐的签名。看起来您正在使用Swift.Result,但改变了通用的Success和Failure类型。您可以将封闭函数发布到要通过完成封闭的位置吗?

OK,尝试将handleResponse更改为:

unc handleResponse(for request: URLRequest,
completion: @escaping (Result<[User], Error>) -> Void) {
... }

并确保ErrorResponse实现 Error

关于php - swift 5错误: “Expected to decode Dictionary<String, Any> but found an array instead.” ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60732894/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com