Greetings. I need to send (receive) data to the server in the background (in background mode). For this I use Background fetch. Below is the code:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { UIApplication.sharedApplication().setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum) return true } func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { sendInform() completionHandler(UIBackgroundFetchResult.NewData) } func sendInform() { let request = NSMutableURLRequest(URL: NSURL(string: "http://dev.superpaperboys.com/aaapi/post.php")!) request.HTTPMethod = "POST" let postString = "login=log&password=pas"; request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding) let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in if error != nil { print("error=\(error)") return } let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding) print("responseString = \(responseString)") } task.resume() } It happens that the request is executed and I see
responseString = Optional({"login":"log","password":"pas"}) It happens that the request is not executed until I enter the application. Sometimes the following error occurs:
error=Optional(Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x15ee81630 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=http://dev.superpaperboys.com/aaapi/post.php, NSErrorFailingURLKey=http://dev.superpaperboys.com/aaapi/post.php, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}) I can not see the pattern. Can anyone come across this problem. I would be grateful for any help.