Get Response using Alamofire - ios

I am using Alamofire to make Get Response but unable to get the Valid Response . I am using below details . I dono where i am making mistake.
let myID = MEGHA-WORK SE-107
let headers = ["Authorization": "Basic \(base64Credentials)" , "ID": (myID).trimmingCharacters(in: .whitespaces) ]
let parameters:Parameters = ["ID": (myID).trimmingCharacters(in: .whitespaces)]
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 60
manager.request(url, method: .get, parameters: parameters, encoding: URLEncoding.queryString , headers: headers).responseJSON { (response) in
debugPrint(response)
if response.response?.statusCode == 200 || response.response?.statusCode == 201 {
if let value = response.result.value {
let json = JSON(value)
print(json)
completion(json, nil)
}
}
Task <343CF648-7C9A-4E03-9A82-A88BC41EA926>.<6> finished with error - code: -1005
Response
[Request]: GET https://my-services.myservices.com:443/prweb/api/v1/cases?ID=MEGHA-WORK%20SE-107
[Response]: nil
[Data]: 0 bytes
[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={NSUnderlyingError=0x109ce9500 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x10d53db00 [0x1b271c310]>{length = 16, capacity = 16, bytes = 0x100201bba06d196d0000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=https://my-services.myservices.com:443/prweb/api/v1/cases?ID=MEGHA-WORK%20SE-107, NSErrorFailingURLKey=https://my-services.myservices.com:443/prweb/api/v1/cases?ID=MEGHA-WORK%20SE-107, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSLocalizedDescription=The network connection was lost.}
[Timeline]: Timeline: { "Request Start Time": 553592494.567, "Initial Response Time": 553592497.615, "Request Completed Time": 553592497.615, "Serialization Completed Time": 553592497.616, "Latency": 3.049 secs, "Request Duration": 3.049 secs, "Serialization Duration": 0.000 secs, "Total Duration": 3.049 secs }

It seems that the reason is already printed there:
Code=-1005 "The network connection was lost."
Restarting the simulator and erasing all content and settings seems to fix this for others (Simulator->Hardware->Erase All Content and Settings...)
Please check this thread.

You can handle this way :
if (responseJson.response?.statusCode)! > 200 && (responseJson.response?.statusCode)! < 300{
// handle as appropriate because the response will be success
} else {
}
It may helps you to handle the crash. Thank you

Related

How to check Alamofire failure of bad internet connection?

How can i check if my Alamofire request Failed because of bad internet connection? I get an error but how can i know that it failed because of that
Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x6000007fe6a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey={length = 28, capacity = 28, bytes = 0x1c1e1f96000000000000000000000000 ... 0000000100000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalUploadTask .<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalUploadTask .<1>"
)
You can get the error message from the failure case like this
Alamofire.request("YourURL", method: .post, parameters: parameters)
.responseJSON { response in
if case .failure(let error) = response.result {
print(error.localizedDescription)//The network connection was lost.
} else if case .success = response.result {
print(response.result.value)
}
}
You can check the failure reason through the underlyingError property from AFError as follows
Alamofire.request("url", method: .post, parameters: parameters)
.responseJSON { response in
if let afError = response.error,
let underlyingError = afError.underlyingError as? URLError {
switch underlyingError.code {
case URLError.notConnectedToInternet:
// do your thing here
default:
// any other URLError code handling
}
}

Alamofire: FAILURE responseSerializationFailed

I'm trying to get the JSON from a URL to download using Alamofire.
Alamofire.request(requrl, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
print(response.result)
print(response.value)
debugPrint(response)
}
However the value of response.value is nil, and the request result status is FAILURE. The following is in the logs:
>[Data]: 919 bytes
[Result]: FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
[Timeline]: Timeline: { "Request Start Time": 561988246.258, "Initial Response Time": 561988246.446, "Request Completed Time": 561988246.447, "Serialization Completed Time": 561988246.447, "Latency": 0.189 secs, "Request Duration": 0.189 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.190 secs
The JSON url in a browser returns:
php script
<?php
header('Content-type: application/json');
//header('Content-Type: html; charset=utf-8');
$sqlstatement = $_GET["sqlstatement"];
// Create connection
$dbConnection=mysqli_connect("***.***.gear.host","****","*****!","****");
//$sqlstatement = "SELECT * FROM reeds.tbl_user";
// Check connection
if (mysqli_connect_errno())
{
// Print error message
echo mysqli_connect_error();
}
// Stores SQL statement, selecting all objects from testcomputing.name
// Check to ensure results > = 1
if ($result = mysqli_query($dbConnection, $sqlstatement))
{
// If so, then create a results array and a temporary one to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($dbConnection);
?>
The issue was associated with the hosting provider. The provider I was originally using had strange security protocols installed, as such no JSON was being returned, after switching it work perfectly.

Alamofire returns "The request timed out" with multipart image upload, but no problems with Postman

I am trying to POST data with an image using multipart upload with Alamofire. But it always returns "The request timed out" error.
When tried the same web service with Postman, it works as it should.
Basically Alamofire keeps trying for sometime,and returns this error, but with Postman I can see that the response is almost immediate and no timeout is recieved.
Here is a the helper method I created for the post request:
class func postRequestWithImage(image: UIImage, params : [String : String],success:#escaping (JSON) -> Void, failure:#escaping (NSError) -> Void){
SVProgressHUD.show()
Alamofire.upload(multipartFormData: { (multipartFormData) in
let imageData : Data = UIImageJPEGRepresentation(image, 0.6)!
for (key, value) in params{
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
multipartFormData.append(imageData, withName: "image")
}, to: WEBSERVICE_URL) { (encodingResult) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
if response.result.isSuccess{
success(JSON(response.result.value!))
SVProgressHUD.dismiss()
}
else{
failure(response.result.error! as NSError)
}
}
case .failure(let encodingError):
failure(encodingError as NSError)
print(encodingError)
}
}
}
The debug response for the same is:
[Request]: http://website.com/v1/service/
[Response]: nil
[Data]: 0 bytes
[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x6080006441a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=http://website.com/v1/service/, NSErrorFailingURLKey=http://website.com/v1/service/, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}
[Timeline]: Timeline: { "Request Start Time": 510773039.719, "Initial Response Time": 510773051.183, "Request Completed Time": 510773120.615, "Serialization Completed Time": 510773120.615, "Latency": 11.464 secs, "Request Duration": 80.895 secs, "Serialization Duration": 0.000 secs, "Total Duration": 80.896 secs }
I solved this. In my case there was a careless mistake. I used an extra slash in the url. I changed the web api to a different folder and while changing it in the iOS code I made this mistake.
I also had some changes made to the .htaccess file, so the request was not giving 404 error but instead trying to connect to that false address. errors that a beginner web developer will make

The data couldn’t be read because it isn’t in the correct format returned when getting google contacts

I am trying to retrieve goole contacts in my swift app and I am getting the error below. The user is successfully singing in.
func getUserContacts(email : String){
let urlString = "http://www.google.com/m8/feeds/contacts/\(email)/full"
Alamofire.request(urlString, method: .get)
.responseJSON { response in
switch response.result {
case .success(let JSON):
print(JSON as! NSDictionary)
case .failure(let error):
print(error.localizedDescription)
}
}
}
(lldb) po "http://www.google.com/m8/feeds/contacts/(email)/full"
"http://www.google.com/m8/feeds/contacts/emailhere#gmail.com/full"
(lldb) po error.localizedDescription
"JSON could not be serialized because of error:\nThe data couldn’t be read because it isn’t in the correct format."
(lldb) po response
▿ [Request]: GET http://www.google.com/m8/feeds/contacts/emailhere.com/full
[Response]: <NSHTTPURLResponse: 0x170033da0> { URL: http://www.google.com/m8/feeds/contacts/emailhere.com/full } { status code: 401, headers {
"Cache-Control" = "private, max-age=0";
"Content-Encoding" = gzip;
"Content-Length" = 8761;
"Content-Type" = "text/html; charset=utf-8";
Date = "Thu, 23 Feb 2017 14:19:11 GMT";
Expires = "Thu, 23 Feb 2017 14:19:11 GMT";
Server = GSE;
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = SAMEORIGIN;
"X-XSS-Protection" = "1; mode=block";
} }
[Data]: 11875 bytes
[Result]: FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
[Timeline]: Timeline: { "Request Start Time": 509552351.480, "Initial Response Time": 509552351.663, "Request Completed Time": 509552351.665, "Serialization Completed Time": 509552351.667, "Latency": 0.183 secs, "Request Duration": 0.185 secs, "Serialization Duration": 0.002 secs, "Total Duration": 0.187 secs }
▿ request : Optional<URLRequest>
▿ some : http://www.google.com/m8/feeds/contacts/emailhere.com/full
▿ url : Optional<URL>
▿ some : http://www.google.com/m8/feeds/contacts/emailhere.com/full
- cachePolicy : 0
- timeoutInterval : 60.0
- mainDocumentURL : nil
- networkServiceType : __ObjC.NSURLRequest.NetworkServiceType
- allowsCellularAccess : true
▿ httpMethod : Optional<String>
- some : "GET"
▿ allHTTPHeaderFields : Optional<Dictionary<String, String>>
- some : 0 elements
- httpBody : nil
- httpBodyStream : nil
- httpShouldHandleCookies : true
- httpShouldUsePipelining : false
▿ response : Optional<NSHTTPURLResponse>
▿ data : Optional<Data>
▿ some : 11875 bytes
- count : 11875
▿ pointer : 0x0000000104e24000
- pointerValue : 4376903680
▿ result : FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
▿ failure : AFError
▿ responseSerializationFailed : ResponseSerializationFailureReason
▿ timeline : Timeline: { "Request Start Time": 509552351.480, "Initial Response Time": 509552351.663, "Request Completed Time": 509552351.665, "Serialization Completed Time": 509552351.667, "Latency": 0.183 secs, "Request Duration": 0.185 secs, "Serialization Duration": 0.002 secs, "Total Duration": 0.187 secs }
- requestStartTime : 509552351.480039
- initialResponseTime : 509552351.66287899
- requestCompletedTime : 509552351.66534299
- serializationCompletedTime : 509552351.66746801
- latency : 0.18283998966217041
- requestDuration : 0.18530398607254028
- serializationDuration : 0.0021250247955322266
- totalDuration : 0.18742901086807251
▿ _metrics : Optional<AnyObject>
my problem was a permissions problem. I added GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/contacts.readonly") and gave my app access in https://myaccount.google.com/security
then this worked:
let urlString = "https://www.google.com/m8/feeds/contacts/default/full?access_token=\(GIDSignIn.sharedInstance().currentUser.authentication.accessToken!)&max-results=\(999)&alt=json&v=3.0"
Alamofire.request(urlString, method: .get)
.validate(contentType: ["application/json"])
.responseJSON { response in
switch response.result {
case .success(let JSON):
var json = JSON as! NSDictionary
print(JSON as! NSDictionary)
case .failure(let error):
print(error.localizedDescription)
}
}

Code=-1001 "The request timed out."

I am working on a Swift project which requires a lot of consumption of APIs. Everything is working fine but sometimes (1 in 20), I get Code=-1001 "The request timed out." error while calling the API.
I am using Alamofire. I am attaching the code to call API.
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = myUrlContents.dataUsingEncoding(NSUTF8StringEncoding)
request.timeoutInterval = 15
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("\(myUrlContents.dataUsingEncoding(NSUTF8StringEncoding)!.length)", forHTTPHeaderField: "Content-Length")
request.setValue("en-US", forHTTPHeaderField: "Content-Language")
Alamofire.request(request)
.validate()
.responseJSON { [weak self] response in
if response.result.isSuccess {
if let result = response.result.value {
print("Result: \(result)")
completion(result: result as! NSDictionary)
}
}
else {
print(response.debugDescription)
}
}
And the log is
[Request]: <NSMutableURLRequest: 0x18855620> { URL: http://....... (url)}
[Response]: nil
[Data]: 0 bytes
[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSErrorFailingURLStringKey=http://.....(url) NSErrorFailingURLKey=http://.....(url), NSLocalizedDescription=The request timed out., _kCFStreamErrorDomainKey=4, NSUnderlyingError=0x18a08900 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102}}}
[Timeline]: Timeline: { "Request Start Time": 493582123.103, "Initial Response Time": 493582138.254, "Request Completed Time": 493582138.254, "Serialization Completed Time": 493582138.256, "Latency": 15.151 secs, "Request Duration": 15.151 secs, "Serialization Duration": 0.002 secs, "Total Duration": 15.153 secs }
I know I can increase the timeout period to avoid the error. But I want to know the actual reason why it is throwing the error. None of my API takes more than 2 seconds to return data. Then why it is showing latency of 15.151 seconds.
I am using LAMP stack on backend. Any help would be appreciated.
I had got the error with Code=-1001 “The request timed out.”.
I tried a few things. Nothing worked. Finally I found out that the problem was in my parameters that I'm sending in the request body to the server which were of wrong format(value was fine but type was wrong). Thats why the request was timing out coz the server wasn't able to process it. You can check that up if nothing else works for u.
I just encountered the same problem. I am using a GET request, and it turns out that using [:] is wrong. You have to use nil in GET request and [:] in POST request

Resources