NSURLSession:后台上传然后调用服务api

时间:2013-10-17 05:59:21

标签: ios ios7 afnetworking nsurlsession

我试图使用新的ios7后台传输API将一些照片上传到服务器。现在发生了什么 1)我们将字节上传到s3 2)调用服务api以“完成”上传

我查看了这个文档,看起来背景NSURLSession不支持'数据'任务。这是否意味着我在实际上传完成后无法在后台执行第2步?

4 个答案:

答案 0 :(得分:4)

如果您想要一个更简单的解决方案而不是重新调整NSURLSessionDownloadTask用于“已完成”的API调用,您可以在回调期间快速回复一次http呼叫:

-URLSession:task:didCompleteWithError:

答案 1 :(得分:3)

对于具有后台任务的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 add

中构建它的方式如下
        - (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");
    }

答案 2 :(得分:0)

NSURLSessions有一个委托方法URLSessionDidFinishEventsForBackgroundURLSession,在会话完成其所有任务后调用。我相信你应该在那里进行api呼叫。

答案 3 :(得分:-2)

- (void)applicationDidEnterBackground:(UIApplication *)application
{

if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
{
    NSLog(@"Multitasking Supported");

    __block UIBackgroundTaskIdentifier background_task;
    background_task = [application beginBackgroundTaskWithExpirationHandler:^ {

        //Clean up code. Tell the system that we are done.
        [application endBackgroundTask: background_task];
        background_task = UIBackgroundTaskInvalid;
    }];

    //To make the code block asynchronous
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        //### background task starts
        NSLog(@"Running in the background\n");
        while(TRUE)
        {
            NSLog(@"Background time Remaining: %f",[[UIApplication sharedApplication] backgroundTimeRemaining]);
            [NSThread sleepForTimeInterval:1]; //wait for 1 sec
        }
        //#### background task ends

        //Clean up code. Tell the system that we are done.
        [application endBackgroundTask: background_task];
        background_task = UIBackgroundTaskInvalid; 
    });
}
else
{
    NSLog(@"Multitasking Not Supported");
}
}

将此代码放入appdelegate.m文件

试试这段代码,希望它会有所帮助。