Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AFNetworking Uploading a file

Does any one have a full implementation of uploading a file using AFNetworking. I have found some code on the internet but it is incomplete. The code I have found is here:

AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://my.client.server.com"]];


NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
[parameters setObject:[fieldName text] forKey:@"field01_nome"];
[parameters setObject:[fieldSurname text] forKey:@"field02_cognome"];



NSMutableURLRequest *myRequest = [client multipartFormRequestWithMethod:@"POST" path:@"/Contents/mail/sendToForm.jsp" parameters:parameters constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:myNSDataToSend mimeType:@"image/jpeg" name:@"alleagto"];
}];


AFHTTPRequestOperation *operation = [AFHTTPRequestOperation HTTPRequestOperationWithRequest:myRequest success:^(id object) {
    NSLog(@"Success");

} failure:^(NSHTTPURLResponse *response, NSError *error) {
    NSLog(@"Fail");

}];


[operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
    NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite);

}];

queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];

I get errors on the following lines:

 [formData appendPartWithFileData:myNSDataToSend mimeType:@"image/jpeg" name:@"alleagto"];

At the myNSDataToSend.

And here:

AFHTTPRequestOperation *operation = [AFHTTPRequestOperation HTTPRequestOperationWithRequest:myRequest success:^(id object) {
    NSLog(@"Success");

} failure:^(NSHTTPURLResponse *response, NSError *error) {
    NSLog(@"Fail");

}];

The error is:

Class method '+HTTPRequestOperationWithRequest:success:failure' not found(return type defaults to 'id')

Any help on this and uploading with AFNetworks would be amazing.

Thanks.

like image 806
iamsmug Avatar asked Nov 22 '11 21:11

iamsmug


1 Answers

First, make sure you have the latest version of AFNetworking downloaded.

AFHTTPRequestOperation +HTTPRequestOperationWithRequest:success:failure: was removed a few versions back. Instead, you can do [[AFHTTPRequestOperation alloc] initWithRequest:...] and then set the completionBlock with either the straight property accessor (operation.completionBlock = ^{...}), or with -setCompletionBlockWithSuccess:failure:. Keep in mind that completion blocks execute after the request has finished downloading.

As for the multipart form block, -appendWithFileData:mimeType:name was also removed a while back. The method you want is -appendPartWithFileData:name:fileName:mimeType:.

Make those two changes and everything should work.

like image 171
mattt Avatar answered Nov 11 '22 21:11

mattt