Data task with URL timed out - ios

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

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.

The network connection is lost only in iOS 13.1.3 (Alamofire)

My app connects to a localhost API through Alamofire. I have implemented URL Scheme, so when I click the link from iMessage it opens my app and in viewDidLoad() it connects to the API. For some reason I am getting following error only in iOS 13.1.3 but it is working smoothly in iOS 12.4. All I am testing in real devices.
Error:
2019-10-21 10:32:13.059194+0530 TestAPI[882:164673] [] nw_read_request_report [C5] Receive failed with error "Software caused connection abort"
2019-10-21 10:32:13.060020+0530 TestAPI[882:164673] Task <45115A48-58C7-49EA-AB5D-2C6708E3C036>.<4> HTTP load failed, 363/0 bytes (error code: -1005 [4:-4])
2019-10-21 10:32:13.076737+0530 TestAPI[882:164603] Task <45115A48-58C7-49EA-AB5D-2C6708E3C036>.<4> finished with error [-1005] Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x283d13840 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x2810a9a40 [0x1d42775e0]>{length = 16, capacity = 16, bytes = 0x100293ddc0a808680000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <45115A48-58C7-49EA-AB5D-2C6708E3C036>.<4>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <45115A48-58C7-49EA-AB5D-2C6708E3C036>.<4>"
), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=http://192.168.8.104:37853/auth/test, NSErrorFailingURLKey=http://192.168.8.104:37853/auth/test, _kCFStreamErrorDomainKey=4}
2019-10-21 10:32:13.590311+0530 TestAPI[882:164306] FBSDKLog: Missing [FBSDKAppEvents appID] for [FBSDKAppEvents publishInstall:]
Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x283d13840 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x2810a9a40 [0x1d42775e0]>{length = 16, capacity = 16, bytes = 0x100293ddc0a808680000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <45115A48-58C7-49EA-AB5D-2C6708E3C036>.<4>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <45115A48-58C7-49EA-AB5D-2C6708E3C036>.<4>"
), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=http://192.168.8.104:37853/auth/test, NSErrorFailingURLKey=http://192.168.8.104:37853/auth/test, _kCFStreamErrorDomainKey=4}
Here is the Code:
override func viewDidLoad()
{
super.viewDidLoad()
txtLable.text = "test"
let testServices = TestService()
let test: Parameters = [
"test": "test"
]
testServices.TestNonSecureConnection(parameters: test, completionHandler: {(returnUserVerificationStatus) -> Void in
if(returnUserVerificationStatus != "failed")
{
self.txtLable.text = returnUserVerificationStatus
}else{
print("failed")
}
})
}
class TestService
{
func TestNonSecureConnection(parameters: Parameters, completionHandler: #escaping (_ returnUserVerificationStatus: String)-> Void )
{
var headers: HTTPHeaders = [:]
var resultString = ""
let url = URL(string: Config.LOGIN_SERVER_URL + "/auth/test")!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
// No-op
}
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request(urlRequest)
.responseString() { response in
switch response.result {
case .success:
resultString = response.result.value!
completionHandler(resultString)
case .failure(let error):
print(error)
}
}
}
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
self.scheme = url.scheme
self.path = url.path
self.query = url.query
let viewController = storyBoard.instantiateViewController(withIdentifier: "viewcontroller") as! ViewController
self.window?.rootViewController = viewController
self.window?.makeKeyAndVisible()
return true
}
Essentially, the underlying NSURLRequest is trying to re-use an HTTP connection that has been dropped by the server. This is apparently caused because the client libraries and your server expect different lifespans for the connection. Or something. Honestly, I'm not 100% sure on the why, but the solutions below all suggest that's what is happening.
There are 3 different ways to solve this one:
Disable KeepAlive on your server
This will cause new connections to be re-created for each new request. Depending on the pattern in which you talk to the server
this may be inconsequential ... or it may be performance concern.
Leave KeepAlive ON but make KeepAliveTimeout longer than 30s
This is
the opposite tradeoff as #1. It will be faster and if you're hitting
the server a lot you may notice it.
This will however cause your server to build up connections and reduce the number of concurrent users you can support. The performance impact of either choice
depends somewhat on what server you're running and you should be
able to decide with a little googling around for "KeepAlive best
practices".
Detect the error code and immediately retry the same query.
When you receive this error - check the error code and immediately retry the
same request. If the error is caused by using a defunct connection, the new query will create a new connection automagically and should work. If the network is genuinely gone the you've got bigger problems.
It's possible that this error will come from other sources, but I've tried all 3 of these approaches and each one solved the issue (obviously with different tradeoffs).
refer to : this post

Checking if song is present in user's Spotify library

Using the below code to check if the user's library contains a particular song. It returns an error. What could I be doing wrong? I couldn't find examples for this particular 'forCheckingIfSavedTracksContains' method anywhere.
let accessToken = SPTAuth.defaultInstance().sessionUserDefaultsKey
let request: URLRequest = try!
SPTYourMusic.createRequest(forCheckingIfSavedTracksContains: ["spotify:track:3ZakaL0QEt5eeD3N7HbaN1"], forUserWithAccessToken: accessToken)
SPTRequest.sharedHandler().perform(request) { (error, response, data) in
if error == nil {
print ("this is data\(String(describing: data))")
} else {
print ("error")
}
}
The error is:
Error Domain=NSURLErrorDomain Code=-1012 "(null)" UserInfo={NSErrorFailingURLStringKey=api.spotify.com/v1/me/tracks/contains?ids=, NSUnderlyingError=0x109e7eb60 {Error Domain=kCFErrorDomainCFNetwork Code=-1012 "(null)" UserInfo={_kCFURLErrorAuthFailedResponseKey=<CFURLResponse 0x109e7e970 [0x1b441e538]>{url = api.spotify.com/v1/me/tracks/contains?ids=}}}, NSErrorFailingURLKey=api.spotify.com/v1/me/tracks/contains?ids=}

SoundCloud API: GET request fails with code -1005, using iOS/Alamofire

I'm working on an iOS app where SoundCloud users log in with OAuth in a web view and then the app makes HTTP requests to the SoundCloud API via Alamofire. I've successfully authenticated the user and stored their token (using ABMSoundCloudAPI), but GET requests to https://api.soundcloud.com/me are failing with a -1005 error, "The network connection was lost." This seems to be a common problem with iOS as discussed here, however resetting the simulator doesn't solve the problem for me and the problem also occurs when using a device. I've also tried:
Removing and re-adding the wifi network
Retrying the request programmatically if it fails
Adding a header with "Connection": "Close"
I see the same error in every case. Are there other headers I should try? I'm using these libraries via Cocoapods:
ABMSoundCloudAPI (0.2.1)
AFNetworking (2.6.1)
AFOAuth2Manager (2.2.0)
Alamofire (3.1.2)
SwiftyJSON (2.3.1)
Here is my code:
var retryCount = 0
func getUserInfo(token:String) {
let headers = ["Connection": "Close"]
Alamofire.request(.GET, "https://api.soundcloud.com/me?oauth_token=\(token)", parameters: ["client_id":clientId], encoding: .JSON, headers: headers)
.responseJSON { response in
guard response.result.error == nil else {
print("error calling GET on /me")
print(response.result.error)
if self.retryCount < 2 {
if let token = self.defaults.stringForKey("sc_key_token") {
self.getUserInfo(token)
++self.retryCount
}
}
return
}
guard let value = response.result.value else {
print("Error: did not receive data")
return
}
let user = JSON(value)
print("User info: " + user.description)
}
}
Error message:
Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={NSUnderlyingError=0x126248c10 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={_kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=https://api.soundcloud.com/me?oauth_token=USER_TOKEN, NSErrorFailingURLKey=https://api.soundcloud.com/me?oauth_token=USER_TOKEN, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSLocalizedDescription=The network connection was lost.}
It seems that this was caused by the request encoding. When I switched from .JSON to .URL, the 1005 error went away.

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