我想从我的应用上传文件到我的服务器。当应用处于活动状态时,以下代码效果很好。如果我按主页按钮或打开另一个应用程序上传停止。
我已启动后台提取功能,但仍无效。
Afnetworking有后台支持,但我无法弄清楚我是如何在我的代码中实现此功能的。
NSString *str=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Archive.zip"];
NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURL fileURLWithPath:str];
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
NSData *imageData=[NSData dataWithContentsOfURL:filePath];
NSMutableURLRequest *request =
[serializer multipartFormRequestWithMethod:@"POST" URLString:@"http://url"
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:@"image"
fileName:@"Archive.zip"
mimeType:@"application/zip"];
}];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFHTTPRequestOperation *operation =
[manager HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure %@", error.description);
}];
[operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
long long totalBytesWritten,
long long totalBytesExpectedToWrite) {
NSLog(@"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation start];
答案 0 :(得分:6)
更改此行
[operation start];
到这个
[operation setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{
// Handle iOS shutting you down (possibly make a note of where you
// stopped so you can resume later)
}];
[manager.operationQueue addOperation:operation];
您可以查看这些链接 AFHTTPRequestOperation doesn't work after stand by mode 和Alternative for enqueueHTTPRequestOperation in AFNetworking 2.0