使用NSURLSession在iPad中上传背景中的照片

时间:2014-08-21 12:12:14

标签: ios7 nsurlsessionuploadtask

使用NSURLSessionUploadTask从资产库上传多张照片的最佳方法是什么?

我现在正在使用NSURLSession后台上传。以下是我使用的代码:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; //getting path of documents directory.
    NSString *documentsPath = [documentsDirectory stringByAppendingPathComponent:@"tempFile.dat"];      //appending file name to documents path.

    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
    {
        ALAssetRepresentation *rep = [myasset defaultRepresentation];
        Byte *buffer = (Byte*)malloc(rep.size);
        NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
        NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];

        _totalBytesToSend += buffered;
        [_dataArray addObject:data];
    };

    ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror)
    {
        DLog(@"Can't get image - %@",[myerror localizedDescription]);
    };

    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];

    //work needed here
    for (NSURL *url in _urlArray) {

        if(url != nil)
        {
            [assetslibrary assetForURL:url
                           resultBlock:resultblock
                          failureBlock:failureblock];
        }

    }

    dispatch_async(dispatch_get_main_queue(), ^(void){
        for (NSData *data in _dataArray) {

            if(![data writeToFile:documentsPath atomically:YES])
            {
                DLog(@"Saving image failed");
            }

            //Prepare upload request
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"my url here"]];
            [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
            [request setHTTPMethod:@"POST"];
            [request addValue:[[DTETokenManager sharedManager] loginToken] forHTTPHeaderField: @"X-CSRF-Token"];

            _uploadTask = [_session uploadTaskWithRequest:request fromFile:[NSURL URLWithString:[NSString stringWithFormat:@"file://%@", documentsPath]]];
            [_uploadTask resume];
        }
    });

这是一个好方法吗?我面临的一个问题是,我无法正确更新进度条,我打算在其中显示整个上传过程的进度。我使用以下代码:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{

    //Progress reportpo
    _totalByteSent += totalBytesSent;
    if(_totalBytesToSend && _totalByteSent)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kBytesUploaded object:nil userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithDouble:(double)totalBytesSent/(double)totalBytesExpectedToSend] forKey:NOTIFICATION_PAYLOAD]];
    }

}

正如预期的那样,进度更新并不合适:)

请指出一个更好的方法,因为我发现很难找到适当的教程来处理上传。虽然有很多解释背景下载的内容。

1 个答案:

答案 0 :(得分:0)

因为我没有从这里得到任何回复,所以我最终倾倒了进度条并添加了一个活动指示器,当所有下载完成时停止旋转