无法转换类型'Dictionary <string,any =“”>?'的值预期参数类型'数据'

时间:2018-04-14 12:44:43

标签: ios swift completionhandler

我仍然是swift的新手,我正在尝试获取json数据并将其作为我创建的对象传递给下一个视图。但是,我收到此错误无法转换'Dictionary'类型的值?当我尝试使用解码器类时,期望参数类型'数据'。我不知道该怎么做才能解决它。我尝试在完成处理程序中将 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)

    }
}

新错误:

enter image description here

2 个答案:

答案 0 :(得分:2)

您要将JSON反序列化两次无法正常工作。

此错误不会返回Dictionary返回Data,而是会导致错误,但还有更多问题。

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) }
    }
}

您必须在Decodable

中采用ServiceCall
class ServiceCall: NSObject, ServiceCallProtocol, URLSessionDelegate, Decodable { ...

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

答案 1 :(得分:1)

会话任务返回的数据可以使用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>

OR

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

decode方法的第二个参数需要Data类型的参数而不是Dictionary

您必须仅编辑fetchJson的完成情况以返回Bool,数据而不是Bool,字典,并从中删除JSONSerialization代码