我在app中使用afnetworkin上传文件。它在iphon4上工作但在iphon5s中失败了。
我在上传时获得连接== nil。
代码:
-(void) uploadFile:(NSURL *)url withFileName:(NSString *)filename mimeType:(NSString *)mimeType {
HUD = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow];
[self.navigationController.view addSubview:HUD];
// Set determinate mode
HUD.mode = MBProgressHUDModeAnnularDeterminate;
HUD.delegate = self;
HUD.labelText = @"Uploading";
progress = 0.0f;
[HUD showAnimated:YES whileExecutingBlock:^{
while (progress < 100) {
//progress += 0.01f;
HUD.progress = (float)progress/100.0;
usleep(50000);
}
}];
// 1. Create `AFHTTPRequestSerializer` which will create your request.
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
NSError *__autoreleasing *error = NULL;
// 2. Create an `NSMutableURLRequest`.
NSMutableURLRequest *request =
[serializer multipartFormRequestWithMethod:@"POST" URLString:kUploadAPI
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:url
name:@"uploadedfile"
fileName:filename
mimeType:mimeType error:nil];
} error:error];
// 3. Create and use `AFHTTPRequestOperationManager` to create an `AFHTTPRequestOperation` from the `NSMutableURLRequest` that we just created.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
operation = [manager HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[HUD hide:YES];
// handle response
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[HUD hide:YES];
NSLog(@"Failure %@", error.description);
}];
// 4. Set the progress block of the operation.
[operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
long long totalBytesWritten,
long long totalBytesExpectedToWrite) {
//NSLog(@"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
progress = (int)(((float)totalBytesWritten / totalBytesExpectedToWrite) * 100.0);
NSLog(@"Uploading...%d",(int)progress);
}];
// 5. Begin!
[operation start];
}
使用AFnetworking在委托方法中获取错误
- (void)connection:(NSURLConnection __unused *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
dispatch_async(dispatch_get_main_queue(), ^{
if (self.uploadProgress) {
self.uploadProgress((NSUInteger)bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}
});
}
使用NSUrlConnection在委托方法中获取错误
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
///here I'm getting connection == nil
}