我还是 swift 的新手,我正在尝试获取 json 数据并将其作为我创建的对象传递给下一个 View 。但是,我收到此错误无法转换“字典”类型的值?当我尝试使用解码器类时,预期的参数类型为“Data”。我不确定如何修复它。我已尝试在我的完成处理程序中将 Dictionary?' 更改为 Data,但我仍然遇到错误。
这是我的代码:
服务电话
class ServiceCall: NSObject, ServiceCallProtocol, URLSessionDelegate {
let urlServiceCall: String?
let country: String?
let phone: String?
var search: SearchResultObj?
init(urlServiceCall: String,country: String, phone: String){
self.urlServiceCall = urlServiceCall
self.country = country
self.phone = phone
}
func fetchJson(request: URLRequest, customerCountry: String, mobileNumber: String, completion: ((Bool, Dictionary<String, Any>?) -> Void)?){
let searchParamas = CustomerSearch.init(country: customerCountry, phoneNumber: mobileNumber)
var request = request
request.httpMethod = "POST"
request.httpBody = try? searchParamas.jsonData()
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
do {
let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, Any>
let status = json["status"] as? Bool
if status == true {
print(json)
}else{
print(" Terrible failure")
}
} catch {
print("Unable to make an api call")
}
})
task.resume()
}
}
SearchViewModel
func searchDataRequested(_ apiUrl: String,_ country: String,_ phone:String) {
let service = ServiceCall(urlServiceCall: apiUrl, country: country, phone: phone)
let url = URL(string: apiUrl)
let request = URLRequest(url: url!)
let country = country
let phone = phone
service.fetchJson(request: request, customerCountry: country, mobileNumber: phone)
{ (ok, json) in
print("CallBack response : \(String(describing: json))")
let decoder = JSONDecoder()
let result = decoder.decode(SearchResultObj.self, from: json)
print(result.name)
// self.jsonMappingToSearch(json as AnyObject)
}
}
新错误:
最佳答案
您将反序列化 JSON 两次,这是行不通的。
不是返回一个Dictionary
而是返回Data
,这个错误导致了错误,但是还有更多的问题。
func fetchJson(request: URLRequest, customerCountry: String, mobileNumber: String, completion: (Bool, Data?) -> Void) { ...
然后把data任务改成
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
if let error = error {
print("Unable to make an api call", error)
completion(false, nil)
return
}
completion(true, data)
})
和服务电话
service.fetchJson(request: request, customerCountry: country, mobileNumber: phone) { (ok, data) in
if ok {
print("CallBack response :", String(data: data!, encoding: .utf8))
do {
let result = try JSONDecoder().decode(SearchResultObj.self, from: data!)
print(result.name)
// self.jsonMappingToSearch(json as AnyObject)
} catch { print(error) }
}
}
而且你必须在ServiceCall
中采用Decodable
class ServiceCall: NSObject, ServiceCallProtocol, URLSessionDelegate, Decodable { ...
此外,我强烈建议将类模型与代码分离以检索数据。
关于ios - 无法将类型 'Dictionary<String, Any>?' 的值转换为预期的参数类型 'Data',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49831583/