2

Ive been recently trying to get AFNetworking to work as i did with native request, i have been always using AFNetworking for uploading POST or GET.but it never uploaded my image correct. it always uploaded to the server damaged and I've explained about the issue in this reference : Uploading image to server reached damaged using AFNetworking

I've tried to use native NSURLConnection.sendSynchronousRequest with HTTP Body and it has been uploaded and not damaged. and this code fully work but i need it in AFNetworking because it only supports IOS 8 + and for more reasons.

        let baseURL = ""
        let selectedImage = self.userImage.image
        let imageData = NSData(data: UIImageJPEGRepresentation(selectedImage!, 0.5)!)

        let request = NSMutableURLRequest()
        request.URL = NSURL(string: baseURL)
        request.HTTPMethod = "POST"
        request.addValue("image/jpeg", forHTTPHeaderField: "Content-Type")
        let body = NSMutableData(data: imageData)
        request.HTTPBody = body

 do {
            let responseData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:nil)
            let responseString = String(data: responseData, encoding: NSUTF8StringEncoding)

            print("User image successfully uploaded navigating to home services")


        } catch (let error as NSError) {
}
Community
  • 1
  • 1
Nata Mio
  • 2,168
  • 3
  • 22
  • 46
  • By the way, if your project is in Swift, you should perhaps use AlamoFire instead of AFNetworking (Source: this SO answer http://stackoverflow.com/a/32988602/433373 ) – Nicolas Miari Jan 21 '16 at 07:43
  • it does the same work, i just need to send HTTP Body and library's doesn't matter. – Nata Mio Jan 21 '16 at 07:58

2 Answers2

0

Following is a solution in Objective-c, replicate the same process for swift too. Create a object for AFHTTPRequestOperationManager as shown below.

 [[AFHTTPRequestOperationManager alloc] initWithBaseURL:@"www.google.com"];

Now define NSDictionary with key value pairs which will be parameters for your request body.

NSDictionary *parameters = @{
                             @"paramaname": value,
                             @"paramaname":value
                        };

Now , when calling POST request

 [self.manager POST:@"someMethodName" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSDictionary * responseDict = (NSDictionary *)responseObject;
    NSLog(@"responseDict : %@",responseDict);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"error  : %@ code %d",error.localizedDescription,error.code);
    }
}];

This is how you can send POST request with parameters using AFNetworking.

AskIOS
  • 918
  • 7
  • 19
  • 1
    i didn't ask how to send post request with AFNetworking, i am asking how can i set http body request in AFNetworking... – Nata Mio Jan 21 '16 at 07:44
  • dictionary parameters which you are setting are the body of your request. Hope you can understand – AskIOS Jan 21 '16 at 07:45
  • `NSURLConnection.sendSynchronousRequest` works well but can i set like HTTPBody in AFNetworking ? dictionary doesn't work like the HTTPBody ! either make your code useful or delete it because it does nothing new. – Nata Mio Jan 21 '16 at 07:55
0
     NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
    [contentDictionary setValue:@"name" forKey:@"email"];
    [contentDictionary setValue:@"name" forKey:@"username"];
    [contentDictionary setValue:@"name" forKey:@"password"];
   [contentDictionary setValue:@"name" forKey:@"firstName"];
    [contentDictionary setValue:@"name" forKey:@"lastName"];

    NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:data
                                          encoding:NSUTF8StringEncoding];
NSLog(@"%@",jsonStr);

NSString *urlString = [NSString stringWithFormat:@"http://testgcride.com:8081/v1/users"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
   [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"moinsam" password:@"cheese"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

AFHTTPRequestOperation *operation = [manager    HTTPRequestOperationWithRequest:request success:<block> failure:<block>];

try this one