AFNetworking background file upload

一个人想着一个人 提交于 2019-12-30 04:32:12

问题


I want to upload files to my server from my app. The code below is working great when app is active. If I press home button or open another app uploading stops.

I activated background fetch but still not working.

Afnetworking has background support but I cant figure out how I implement this feature to my code.

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];

回答1:


Change this line

[operation start];

to this

[operation setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{
        // Handle iOS shutting you down (possibly make a note of where you
        // stopped so you can resume later)
    }];


    [manager.operationQueue addOperation:operation];

You can look at these links AFHTTPRequestOperation doesn't work after stand by mode and Alternative for enqueueHTTPRequestOperation in AFNetworking 2.0



来源:https://stackoverflow.com/questions/25829236/afnetworking-background-file-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!