計時器的想法將工作。通過定時器以適合您的應用程序的某個間隔調用數據管理器類的uploadOutstandingObjects
假設您有一個需要上傳的'Foo'實體。您可以在您的數據管理器類中執行以下操作...
- (void)uploadOutstandingObjects {
// I use the great MagicalRecord class for Core Data fetching
// https://github.com/magicalpanda/MagicalRecord
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"status == pending"]
NSArray *outstandingObjects = [Foo MR_findAllWithPredicate:predicate];
for (Foo *foo in outstandingObjects) {
[foo uploadToServer];
}
要做到這一點的一種方法是使用通知。每當您開始上傳時,您都會讓該對象收聽「uploadsStopped」通知。上傳完成後,上傳的對象將停止監聽。
Foo類:
- (void)uploadFailed {
// change status to upload pending in the database for this 'foo' object
}
- (void)uploadComplete {
// change status to upload complete in the database for this 'foo' object
}
-(void)uploadToServer {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(uploadFailed:)
name:@"uploadsStoppedNotification"
object:nil ];
// perform upload. If you are doing this synchronously...
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:<url here>];
[request startSynchronously];
if (![request error]) {
[self uploadSucceeded];
// stop listening to global upload notifications as upload attempt is over
[NSNotificationCenter removeObserver:self];
}
else {
[self uploadFailed];
// stop listening to global upload notifications as upload attempt is over
[NSNotificationCenter removeObserver:self];
}
如果您的應用程序退出,你可以處理不斷變化尚未完成
- (void)applicationDidEnterBackground:(UIApplication *)application {
// this will fire to any objects which are listening to
// the "uploadsStoppedNotification"
[[NSNotificationCenter defaultCenter]
postNotificationName:@"uploadsStoppedNotification"
object:nil ];