我多次尝试并失败了,以获取一些继承的代码以成功发送后台会话请求。在前台时,它可以完美运行,但在后台,它要么永远不会返回,要么在某些情况下会收到身份验证挑战。
创建请求的代码非常样板:
NSURLSessionConfiguration *sessionConfig =
[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:identifier];
sessionConfig.sessionSendsLaunchEvents = true;
sessionConfig.discretionary = false;
sessionConfig.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
sessionConfig.timeoutIntervalForResource = 60 * 60 * 24; //One day. Default is 7 days!
/* Create session, and optionally set a NSURLSessionDelegate. */
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig
delegate:self
delegateQueue:[NSOperationQueue mainQueue]];
NSURLComponents *urlComponents = [NSURLComponents new];
urlComponents.scheme = @"https";
urlComponents.host = @"jsonplaceholder.typicode.com";
urlComponents.path = @"/posts/1";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[urlComponents URL]];
request.HTTPMethod = @"PUT";
NSLog(@"Making request: %@", request);
/* Start a new Task */
NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
[task resume];
但我从来没有得到任何回报。我确实有所需的背景模式(可能)
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>remote-notification</string>
</array>
我的代表正在委派一切
<NSURLSessionDelegate, NSURLSessionDataDelegate,NSURLConnectionDataDelegate,NSURLConnectionDelegate,NSURLSessionTaskDelegate>
任何帮助将不胜感激 - 我很确定我在某处只缺少一行代码。我什至甚至创建了一个 GitHub 存储库来测试此代码 - 它安排了本地通知以允许您在后台运行会话任务。