【发布时间】:2014-09-14 01:15:35
【问题描述】:
我想从我的应用程序上传文件到我的服务器。当应用程序处于活动状态时,下面的代码运行良好。如果我按主页按钮或打开另一个应用程序上传停止。
我激活了后台提取但仍然无法正常工作。
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];
【问题讨论】:
-
您能找到解决这个问题的方法吗?
-
从苹果 NSURLSession 文档中,后台传输只支持上传和下载任务(没有数据任务)的文件 URL,根据你的代码看来你正在使用 NSData 上传。
标签: objective-c file-upload afnetworking background-process