我正在使用 sendAsynchronousRequest:queue:completionHandler: 上传文件(我已经删除了一些旧的第三方库,以支持使用此本机方法直接调用。我保留了 NSURLRequest 和字典原样。)。我不知道如何判断它是如何完成推送文件的。我认为在将定期调用的完成处理程序中,我们可以检查传入的参数,但它们似乎不包含我需要的内容。
- (void)sendToServer:(NSString*)url asset:(MYAsset *)asset path:(NSString *)file completion:(MYUploaderBoolBlock)completion{
NSDictionary *uploadParameters = asset.s3Info;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:uploadParameters[@"my_url"]]];
request.HTTPMethod = @"PUT";
request.timeoutInterval = 300;
[request addValue:uploadParameters[@"date"] forHTTPHeaderField:@"Date"];
[request addValue:uploadParameters[@"authorization"] forHTTPHeaderField:@"Authorization"];
[request addValue:uploadParameters[@"content_type"] forHTTPHeaderField:@"Content-Type"];
[request addValue:asset.md5 forHTTPHeaderField:@"Content-MD5"];
[request addValue:@"public-read" forHTTPHeaderField:@"x-amz-acl"];
[request addValue:[@(asset.sizeInKB) stringValue] forHTTPHeaderField:@"Content-Length"];
request.HTTPBodyStream = [NSInputStream inputStreamWithFileAtPath:file];
DDLogInfo(@"Uploading %@ to server", uploadParameters[@"my_url"]);
DDLogInfo(@"HTTP Headers: %@", [request allHTTPHeaderFields]);
[NSURLConnection sendAsynchronousRequest:request
queue:self.queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if ([data length] > 0 && error == nil){
// I am expecting that this can be used to detect progress of the file upload
// as well as completion?
NSLog(@"received data %d/%d =%f%", data.length, response.expectedContentLength, data.length/(float)response.expectedContentLength);
if(data.length == response.expectedContentLength){
// This never fires because expectedContentLength is always -1
completion(YES);
}
}
else if ([data length] == 0 && error == nil){
NSLog(@"reply empty");
}
else if (error != nil && error.code == -1001){
NSLog(@"timed out");
}
else if (error != nil){
NSLog(@"Error %@", error.localizedDescription);
completion(NO);
}
}];
}