Xcode : Alamofire get String response

别来无恙 提交于 2019-12-04 00:40:19

问题


I am new in IOS development and currently learning networking with Alamofire

i am trying to make a login ... whenever the credentials are correct the .php file returns a json and i am able to get that json from Alamofire through the following code:

    Alamofire.request(loginUrl, method: .post, parameters: parameters).responseJSON { (response:DataResponse<Any>) in
        print("String:\(response.result.value)")
        switch(response.result) {
        case .success(_):
            if let data = response.result.value{
                print(self.loginUrl)
                print(data)
            }

        case .failure(_):

            print(self.loginUrl)
            print("failed")
            print("Error message:\(response.result.error)")
            break

        }
    }

now...when ever the credentials are wrong, the .php does't give the json..instead it return a string ..for example "wrong_password" or "userLocked" etc etc... how can i get the String response through Alamofire?


回答1:


If you want JSON response use .responseJSON , if you want String response use .responseString. If you want both use both. Hope this help.

Alamofire.request(loginUrl, method: .post, parameters: parameters)
     .responseJSON { response in
       print("JSON:\(response.result.value)")
       switch(response.result) {
       case .success(_):
          if let data = response.result.value{
             print(data)
           }

        case .failure(_):

            print("Error message:\(response.result.error)")
            break

        }
    }
     .responseString { response in
       print("String:\(response.result.value)")
       switch(response.result) {
       case .success(_):
          if let data = response.result.value{
             print(data)
            }

       case .failure(_):
           print("Error message:\(response.result.error)")
           break     
        }
    }



回答2:


I resolve this by:

print(response.request)  // original URL request
print(response.response) // URL response
print(response.data)     // server data
print(response.result)   // result of response serialization

source: https://github.com/Alamofire/Alamofire/issues/818



来源:https://stackoverflow.com/questions/44095161/xcode-alamofire-get-string-response

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!