簡體   English   中英

無法轉換“字典”類型的值 <String, Any> ? 到預期的參數類型“數據”

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

我仍然對Swift還是陌生的,我試圖獲取json數據並將其作為我創建的對象傳遞給下一個視圖。 但是,我收到此錯誤無法轉換類型為“字典”的值? 當我嘗試使用解碼器類時,將其轉換為預期的參數類型“數據” 我不確定該如何解決。 我嘗試過更改字典嗎? 到我的完成處理程序中的數據,但仍然出現錯誤。

這是我的代碼:

服務電話

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

然后將數據任務更改為

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

此外,我強烈建議將類模型與代碼分開以檢索數據。

從會話任務返回的數據可以使用JSONSerialization進行序列化,也可以使用JSONSerialization對其進行解碼

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

解碼方法的第二個參數需要一個參數類型為Data not Dictionary的參數

您只需編輯fetchJson的完成即可返回Bool,Data而不是Bool,Dictionary,並從其中刪除JSONSerialization代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM