AFNetworking在后台上传文件

时间:2014-09-25 22:06:57

标签: objective-c afnetworking afnetworking-2

我需要能够上传多个视频文件并让它在应用程序变为非活动状态时继续工作(按下主页按钮等等)这是我正在使用的代码,但是当我离开时,这会暂停上传应用程序和简历,当我回来时:

NSMutableArray *mutableOperations = [NSMutableArray array];
for(ClipForUpload *clip in items){
    NSString *path = NSTemporaryDirectory();
    path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-%i.mov", clip.media_link_guid, self.onClip]];
    NSUserDefaults *fetchDefaults = [NSUserDefaults standardUserDefaults];
    NSString *busToken = [fetchDefaults objectForKey:@"ActiveBusiness"];
    NSString *userToken = [fetchDefaults objectForKey:@"UserToken"];
    NSString *authValue = [NSString stringWithFormat:@"Token %@", userToken];

    //now put the video
    NSString *partUrl = [NSString stringWithFormat:@"https://api.com/%@/media/stockfootage/%@/", busToken, clip.token];
    NSMutableURLRequest *req = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"PUT" URLString:partUrl parameters:@{} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"media_file" error:nil];
    } error:nil];
    [req setValue:authValue forHTTPHeaderField:@"Authorization"];
    [req setTimeoutInterval:12000];
    AFHTTPRequestOperation *oper = [[AFHTTPRequestOperation alloc] initWithRequest:req];
    [oper setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        float pct = ((float)totalBytesWritten/totalBytesExpectedToWrite) * 100;
        pct = roundf(pct);
        NSLog(@"%f", pct);
        dispatch_async(dispatch_get_main_queue(), ^{
            MBProgressHUD *hud = [MBProgressHUD HUDForView:self.view];
            hud.labelText = [NSString stringWithFormat:@"Uploading Clip %i of %i - %g%%", self.onClip + 1, (int)items.count, pct];
        });
    }];
    [mutableOperations addObject:oper];
}

NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:mutableOperations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
    self.onClip++;
    NSLog(@"DONE WITH A CLIP");
} completionBlock:^(NSArray *operations) {
    NSLog(@"All operations in batch complete");

}];
NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init];
operationQueue.maxConcurrentOperationCount = 1;
[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];

有没有办法修改此代码,以便上传继续而不是暂停?

0 个答案:

没有答案