2013-10-09 97 views
6

我一直在尋找新的AFNetworking 2.0上傳圖片的例子。 但是我打牆,無法弄清楚代碼有什麼問題。 所以這是我用通過AFNetworking 2.0上傳iOS圖片

NSData *imageData = UIImageJPEGRepresentation(image, 0.5); 
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 


AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 

NSURL *URL = [NSURL URLWithString:@"http://myserverurl.com"]; 

NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 

NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromData:imageData progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 
    if (error) { 
     NSLog(@"Error: %@", error); 
    } else { 
     NSLog(@"Success: %@ %@", response, responseObject); 
    } 
}]; 
[uploadTask resume]; 

TIA代碼

+0

以何種方式這難道不是工作?你有錯誤嗎? –

回答

34

我結束了使用多部分請求

UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage]; 
NSData *imageData = UIImageJPEGRepresentation(image, 0.5); 
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
NSDictionary *parameters = @{@"foo": @"bar"}; 
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
    [formData appendPartWithFormData:imageData name:@"image"]; 
} success:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSLog(@"Success: %@", responseObject); 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"Error: %@", error); 
}]; 
+3

'appendPartWithFileData:imageData名稱:@「image」錯誤:無]'不再工作了,我想。你應該使用:'[formData appendPartWithFormData:imageData name:@「image」];'...但它仍然不適用於我:/ – raistlin

+4

爲什麼你甚至不打算在fileURl之後使用它? – raistlin

+2

@raistlin'appendPartWithFileData'也適用於我。看到http://stackoverflow.com/a/20190352/1933185 – jerik