Code=-1001 "The request timed out." - ios

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

Related

Get Response using Alamofire

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

Alamofire post method in iOS Swift 4?

For getting push notification here i am sending postitem, token, like count and currentname using alamofire post method(pod version alamofire 4.5). I did not get any response when post method called and it does not show any errors.
I tried keeping breaking points in alamofire function, it call alamofire.requestion then it goes out function.
Here is the code tried to send post method to backend:
func postNotification(postItem: String, post: Post) {
print("Get token from post:::",post.token)
print(postItem)
let token = UserDefaults.standard.string(forKey: "token")
let headers: HTTPHeaders = ["Content-Type" :"application/x-www-form-urlencoded"]
let parameters : [String:Any] = ["count":post.likeCount!, "likedby":currentName, "postId=":postItem, "token": post.token!]
Alamofire.request("http://highavenue.co:9000/likesnotification/", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if let data = response.result.value{
print(data)
}
break
case .failure(_):
print(response.result.error as Any)
break
}
}
}
Getting console error like this
2018-07-10 14:21:07.980212+0530 HighAvenue[10584:4236493] Task <B5FC98AB-C3FE-
4D4F-9A93-72D3FFE35DF7>.<1> finished with error - code: -1001
Optional(Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."
UserInfo={NSUnderlyingError=0x1c0e478f0 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=http://highavenue.co:9000/likesnotification/, NSErrorFailingURLKey=http://highavenue.co:9000/likesnotification/, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.})
That is because you are not setting request time in your network call, by default your request time is a small interval, so please increase request timeout time. something like this,
let request = NSMutableURLRequest(url: URL(string: "")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.timeoutInterval = 120 // 120 secs
let values = ["key": "value"]
request.httpBody = try! JSONSerialization.data(withJSONObject: values, options: [])
Alamofire.request(request as! URLRequestConvertible).responseJSON {
response in
// do whatever you want here
}
Second mistake in your code is you are trying to access http url which are by default are not allowed so you have to by pass this security from your app, Please refer to this answer in order to remove this security layer from your app.
The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

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

Data task with URL timed out

I am trying to access a website. I am using a dataTaskWithURL request.
Here is my code:
let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in
print("2")
if let urlContent = data {
print("3")
let stringContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding)!
let arr = stringContent.componentsSeparatedByString("<b>The computer's solutions will appear below</b><br>")
let second = arr[1]
let newArr = second.componentsSeparatedByString("</tr></table></center><p align=\"center\">")
let results = newArr[0]
self.resultsLabel.text = results
self.stopActivity()
} else {
print(error)
self.stopActivity()
}
})
task.resume()
I have also tried running this code on the main block:
dispatch_async(dispatch_get_main_queue(), {() -> Void in
// Code
})
However, neither of these has been successful. I repeatedly get the following error
Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x7ff0a3f4c6e0 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=THE URL I AM TRYING TO ACCESS, NSErrorFailingURLKey=THE URL I AM TRYING TO ACCESS, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.})
I have tried looking at this post and this one as well. However, I have not been successful with them. The website loads fairly quickly. How do I get rid of this error?
It could be caused by a number of things; If the issue is happening in the Simulator, I suggest restarting it as per the suggestions in the SO posts below:
Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."
Error: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."
NSURLErrorDomain Code=-1001 error when a http post request is sent
Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit
How to use NSURLSessionDataTask in Swift
It might be help to print response as well to see if the HTTP headers can provide a clue.
I realized that I was using https:// instead of http://.

Request Timed out with Code=-1001_kCFStreamErrorCodeKey=-2102

Sometimes network request from my app gets stuck, And I get the following error after a while,
failed with error: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."UserInfo={NSUnderlyingError=0x1390937f0 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=https://apis.xyz.xyz.com, NSErrorFailingURLKey=https://apis.xyz.xyz.com, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}
Any request I make after this, The same sent request is sent out and it fails with same error. So, no new request goes out. This happens very rarely, but it does happen.
I am using NSURLSessionDataTask:dataTaskWithRequest:completionHandler to make a network calls.
Method 1: set timeoutIntervalForRequest in sessionConfig:
let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = 180 // use a bigger number if needed
let session = URLSession(configuration: sessionConfig)
let task = session.dataTask(with: request, completionHandler: { data, response, error in
completionHandler(data, response, error)
})
Method 2: set timeoutInterval for request:
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.timeoutInterval = 180 // use a bigger number if needed
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
completionHandler(data, response, error)
})
Increase the timeout interval like 150 secs .

Resources