在后台使用NSURLSession时,不确定我的应用程序对象会发生什么 - 我的应用程序处于什么状态?

时间:2014-08-21 15:30:17

标签: ios nsurlsession nsurlsessionconfiguration nsurlsessionuploadtask

更多一般性问题 - 在NSURLSession"中使用background session mode时,我不了解@interface ProfilePicture : NSObject @property int userId; @property UIImage *profilePicture; @property BOOL successfullyUploaded; // we want to know if the image was uploaded to out server - this could also be a property that is queryable but lets assume this is attached to this object @end 的工作原理。我将提供一些简单的人为示例代码。

我有一个保存对象的数据库 - 这样可以将部分数据上传到远程服务器。重要的是要知道上传了哪些数据/对象以便准确地向用户显示信息。能够在后台任务中上传到服务器也很重要,因为应用程序可以在任何时候被杀死。

例如一个简单的个人资料图片对象:

@implementation ProfilePictureUploader

-(void)uploadProfilePicture:(ProfilePicture *)profilePicture completion:(void(^)(BOOL successInUploading))completion
{
     NSUrlSession *uploadImageSession = ..... // code to setup uploading the image - and calling the completion handler;
     [uploadImageSession resume];
}

@end

现在让我们说我想将个人资料图片上传到远程服务器 - 我可以这样做:

ProfilePicture *aNewProfilePicture = ...;
aNewProfilePicture.profilePicture = aImage;
aNewProfilePicture.userId = 123;
aNewProfilePicture.successfullyUploaded = NO;

// write the change to disk
[MyDatabase write:aNewProfilePicture];

// upload the image to the server
ProfilePictureUploader *uploader = [ProfilePictureUploader ....];
[uploader uploadProfilePicture:aNewProfilePicture completion:^(BOOL successInUploading) {
  if (successInUploading) {
    // persist the change to my db.
    aNewProfilePicture.successfullyUploaded = YES;
    [Mydase update:aNewProfilePicture]; // persist the change 
  }
}];

现在我的代码中的其他地方我想上传个人资料图片 - 如果成功,请更新此操作发生的用户界面和数据库:

ProfilePicture

现在很明显,如果我的应用程序正在运行,那么这个" aNewProfilePicture"对象成功上传,一切都很好 - 数据库对象有自己的内部工作与数据结构/缓存,什么不是。维护可能存在的所有回调,并且应用程序状态很简单。

但我不清楚如果该应用程序死亡会发生什么?#34;在上传期间的某个时刻。似乎任何回调/通知都已死亡。根据API文档 - 上传由单独的流程处理。因此,上传将继续,我的应用程序将在未来的某个时刻被唤醒以处理完成。但是对象" successfullyUploaded"在那一点上是不存在的并且所有回调/对象都消失了。我不明白此时存在什么背景。我如何确保我的数据库和用户界面的一致性(例如更新该用户的" {{1}}"属性)?我是否需要重新处理触及数据库或用户界面的所有内容以与新API对应并在无上下文环境中工作?

1 个答案:

答案 0 :(得分:0)

您可以使用带有后台配置的NSURLSession下载和上传文件。您必须实现NSURLSessionDelegate,NSURLSessionDownloadDelegate,NSURLSessionUploadDelegate。使用后台会话,您无法再使用完成处理程序。我发现本教程非常有助于理解NSURLSession背景的工作原理: http://www.appcoda.com/background-transfer-service-ios7/

在您的情况下,您可以执行以下操作:创建上传任务时,您可以将数据库中的用户ID分配给“任务描述”。你的NSURLSessionTask的属性。上传完成后,调用委托方法,您可以实现以下内容:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
   int userID = [task.taskDescription intValue];
   [self.database updateUserRecordWithID:userID];
}