簡體   English   中英

如何在快速的 iOS 請求中獲得數組響應

[英]How to get array response in swift iOS Request

我發送這樣的請求:

let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                // check for fundamental networking error
                print("error=\(String(describing: error))")
                completion(nil)
                return
            }


            print("********_Respone status code is: ",(response as! HTTPURLResponse).statusCode)
            print("********_Respone url code is: ",response?.url as Any )

            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]

                let res:HTTPURLResponse = response as! HTTPURLResponse

                print(json)// yessssssssss goooood
            } catch {
                completion(nil)
                return
            }
}


        task.resume()

當響應是字典時它可以正常工作,但是當我的響應是數組時顯示此錯誤:

無法將“__NSArrayI”類型的值轉換為“NSDictionary”

請幫我解決這個問題。

將 JSON 反序列化一次並省略選項, ArrayDictionary are not fragmented 然后可選綁定結果。

do {
     let json = try JSONSerialization.jsonObject(with: data)
     if let jsonArray = json as? [[String:Any]] {
        print("json is array", jsonArray)
     } else if let jsonDictionary = json as? [String:Any] {
        print("json is dictionary", jsonDictionary)
     } else {
        print("This should never be displayed")
     }
} ...

如果結果應該只是數組或字典,那么您可以強制將結果解包到字典並刪除最后一個else子句

do {
     let json = try JSONSerialization.jsonObject(with: data)
     if let jsonArray = json as? [[String:Any]] {
        print("json is array", jsonArray)
     } else {
        let jsonDictionary = json as! [String:Any] 
     }
} ...

暫無
暫無

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

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