对于具有后台任务的 S3,请参阅我的回答 here
另一个很好的资源是苹果示例代码here 并寻找“简单后台传输”
您必须创建一个上传任务并从本地文件上传。当您的应用程序正在运行时,NSURLSessionTaskDelegate 委托方法将在完成时调用,特别是在上传完成时:
/* Sent as the last message related to a specific task. Error may be
* nil, which implies that no error occurred and this task is complete.
*/
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error;
如果您的应用程序进入后台甚至被 iOS(而不是用户)杀死,您的应用程序将被唤醒
URLSessionDidFinishEventsForBackgroundURLSession
然后你的 NSURLsession 委托方法会被调用
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
你应该构建它的方式如下,在你的appDelegate中添加
- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
{
/*
Store the completion handler. The completion handler is invoked by the view controller's checkForAllDownloadsHavingCompleted method (if all the download tasks have been completed).
*/
self.backgroundSessionCompletionHandler = completionHandler;
}
然后在你的控制器/模型类中添加
/*
If an application has received an - application:handleEventsForBackgroundURLSession:completionHandler: message, the session delegate will receive this message to indicate that all messages previously enqueued for this session have been delivered. At this time it is safe to invoke the previously stored completion handler, or to begin any internal updates that will result in invoking the completion handler.
*/
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
{
APLAppDelegate *appDelegate = (APLAppDelegate *)[[UIApplication sharedApplication] delegate];
if (appDelegate.backgroundSessionCompletionHandler) {
void (^completionHandler)() = appDelegate.backgroundSessionCompletionHandler;
appDelegate.backgroundSessionCompletionHandler = nil;
completionHandler();
}
NSLog(@"All tasks are finished");
}