简体   繁体   English

如何使用 alamofire 在 iOS swift 中处理空数组响应

[英]How to handle empty array response in iOS swift using alamofire

I am using alamofire for service integration.我正在使用 alamofire 进行服务集成。 its giving an empty reponse as [] sometimes only.它有时仅作为 [] 给出空洞的回应。 in that time app is crashing because of empty array response.那时应用程序因为空数组响应而崩溃。 How to handle that response in swift iOS.如何在 swift iOS 中处理该响应。

Here is my code:这是我的代码:

    let headers = ["Authorization" : "Bearer "+token,
                   "Content-Type": "application/json"]

Alamofire.request(" http://sos.partnersbuddy.in/api/friend_request/received ", method: .get, encoding: JSONEncoding.default, headers: headers).responseJSON { response in // print("Request (response.request)") Alamofire.request(" http://sos.partnersbuddy.in/api/friend_request/received ", method: .get, encoding: JSONEncoding.default, headers: headers).responseJSON { response in // print("Request (response) 。要求)”)

        print("RESPONSE \(String(describing: response.result.value))")
        print("RESPONSE \(response.result)")
        print("RESPONSE \(response)")

            var respVO:[RequestResvo] = Mapper<RequestResvo>().mapArray(JSONArray: response.result.value as! [[String : Any]])

            print(respVO)

            self.postID = respVO[0].id!

            if let result = response.result.value {
                let JSON = result as! NSArray
                print(JSON.value(forKey: "user"))

                let res = JSON.value(forKey: "user")
                let respVo = Mapper<SubRequestVo>().mapArray(JSONArray: res as! [[String : Any]])

                for (index, element) in (respVo.enumerated()) {
                    print(index)

                    self.nameArr.append(element.first_name!)
                    self.numberArr.append(element.mobile!)

                    print("nameArr\(self.nameArr)")                        
                    print("numberArr\(self.numberArr)")

                    DispatchQueue.main.async {
                        // update your UI and model objects here

                        self.mytableView.reloadData()
                        // SKActivityIndicator.dismiss()
                    }
                }
            }
    }

How to handle this empty response in that time app is crashing because of empty array response.如何在应用程序因空数组响应而崩溃时处理此空响应。 How to handle that response in swift iOS.如何在 swift iOS 中处理该响应。

You can try print response as string:您可以尝试将响应打印为字符串:

Add it at the end of your request, like this:在您的请求末尾添加它,如下所示:

Alamofire.request(url, method: .get, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in

}.responseString { response in
    print(response)
}

Looking at your code, I would do something like this:看看你的代码,我会做这样的事情:

Alamofire.request("http://sos.partnersbuddy.in/api/friend_request/received", method: .get, encoding: JSONEncoding.default, headers: headers).responseJSON { response in

        switch response.result {
        case .success(let json):
            guard let array = json as? [[String : Any]] else {
                // Handle error: your json response is not a [[String : Any]] as you were expecting
            }

            if array.count == 0 {
                // Handle empty array response
            }

            var respVO:[RequestResvo] = Mapper<RequestResvo>().mapArray(JSONArray: response.result.value as! [[String : Any]])

            print(respVO)

            self.postID = respVO[0].id!

            if let result = response.result.value {
                let JSON = result as! NSArray
                print(JSON.value(forKey: "user"))

                let res = JSON.value(forKey: "user")
                let respVo = Mapper<SubRequestVo>().mapArray(JSONArray: res as! [[String : Any]])

                for (index, element) in (respVo.enumerated()) {
                    print(index)

                    self.nameArr.append(element.first_name!)
                    self.numberArr.append(element.mobile!)

                    print("nameArr\(self.nameArr)")
                    print("numberArr\(self.numberArr)")

                    DispatchQueue.main.async {
                        // update your UI and model objects here

                        self.mytableView.reloadData()
                        // SKActivityIndicator.dismiss()
                    }
                }
            }
        case .failure(let error):
            // Handle response error
            print(error)
        }
    }

This let you handle both response result and the empty array case.这让您可以处理响应结果和空数组情况。 Giving more information about your response json format, would be better to write down more precise code that fit your problem.提供有关您的响应 json 格式的更多信息,最好写下适合您的问题的更精确的代码。

I got an empty json from alamofire response with nil status code and failure because of sending the URL with spaces.由于发送带有空格的 URL,我从 alamofire 响应中得到一个空的 json,状态码为零,失败。 If you got something similar, make sure to use the url with allowed characters:如果你有类似的东西,请确保使用带有允许字符的 url:

var urlString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM