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

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 .

Related

Why I can't access my nodejs local server from iOs simulator

I am trying to make an http request from my xcode to my local server running on nodejs. The following in a part of my iOs code.
let url = URL(string: "http://localhost.com/signup")!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
print(String(data: data, encoding: .utf8)!)
}
task.resume()
I recieve the following the response
Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."
Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified hostname could not be
found.
I receive the first error if I use localhost.com and I receive the second error if I change the request to www.localhost.com
in this case you have to use your IP to get access to your localhost
ex: let url = URL(string: "http://192.168.1.105/signup")!
so Instead of using (localhost.com/...) you have to set the IP of your computer where you have LOCAL SERVER.

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

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

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://.

Multipart-form data POST to upload image not working after boundary is added in Swift

So I'm trying to do a multi-part post request in Swift using the following format:
user_id 3232424234
photo *PHOTO DATA*
I set up my request as shown at the bottom of this post and am getting the following error:
Optional(Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={NSUnderlyingError=0x7f86235cfe40 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={_kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=ENDPOINTURL, NSErrorFailingURLKey=ENDPOINTURL, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSLocalizedDescription=The network connection was lost.})
This error seems extremely odd to me because I can make it go away by omitting the boundary requirements for the POST request, but the server than explodes with a 500 and lets the client know it omitted the boundary reqs, so yah. I am probably doing something wrong in Swift. Below is my code to make the request. Let me know if more info is needed, thx guru's of the world.
//Inputs in this scope are an "id" and a "photo"
let url = NSURL(string: "**URL**")
let boundary = NSUUID()
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("multipart/form-data; boundary=--\(boundary)", forHTTPHeaderField: "Content-Type")
let parameterBody:NSDictionary = [
"user_id": id,
]
let data:NSMutableData = NSMutableData()
parameterBody.enumerateKeysAndObjectsUsingBlock { (parameterKey: AnyObject, parameterValue: AnyObject, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
data.appendData(NSString(string: "--\(boundary)\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
data.appendData(NSString(string: "\(parameterKey) \(parameterValue)\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
}
data.appendData(NSString(string: "--\(boundary)\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
data.appendData(NSString(string: "photo").dataUsingEncoding(NSUTF8StringEncoding)!)
data.appendData(photo.imageData as! NSData)
data.appendData(NSString(string: "--\(boundary)--\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
request.setValue("\(data.length)", forHTTPHeaderField: "Content-Length")
let task = NSURLSession.sharedSession().uploadTaskWithRequest(request, fromData: data) { (responseJSON: AnyObject?, response: NSURLResponse?, error: NSError?) -> Void in
//Here I handle the response and check for errors.
}
task.resume()
There are a ton of issues here:
The boundary should be NSUUID().UUIDString.
When you add the boundary to the Content-Type header, you should not add -- there.
The individual parts of the multipart request are not well-formed. For example, you're missing the Content-Disposition.
It's not critical, but you do not need to set Content-Length of the request. That's done for you.
I'd suggest you refer to this answer which provides example of how to form multipart request: Upload image with parameters in Swift. Or consider using Alamofire, which takes care of all of this for you.

Resources