无法将类型 'Dictionary<String, Any>?' 的值转换为预期的参数类型 'Data'

Cannot convert value of type 'Dictionary<String, Any>?' to expected argument type 'Data'

我还是 swift 的新手,我正在尝试获取 json 数据并将其作为我创建的对象传递给下一个视图。但是,当我尝试使用解码器 class 时,出现此错误 无法将类型 'Dictionary?' 的值转换为预期的参数类型 'Data'。我不确定如何修复它。我已尝试在我的完成处理程序中将 Dictionary?' 更改为数据,但我仍然遇到错误。

这是我的代码:

服务电话

    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)

    }
}

新错误:

来自会话任务的数据 return 可以使用 JSONSerialization 序列化或使用 JSONDecoder

解码
 let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in

或者

 let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, Any>

let result = try  decoder.decode([item].self,data!)

decode 方法的第二个参数需要 Data 而非 Dictionary

类型的参数

您只需将 fetchJson 的完成编辑为 return Bool,Data 而不是 Bool,Dictionary,并从中删除 JSONSerialization 代码

您将反序列化 JSON 两次,这是行不通的。

而不是returning一个DictionaryreturnData,这个错误导致了错误,但是还有更多的问题。

func fetchJson(request: URLRequest, customerCountry: String, mobileNumber: String, completion: (Bool, Data?) -> Void) { ...

然后将数据任务改为

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 { ...

此外,我强烈建议将 class 模型与检索数据的代码分开。