简体   繁体   中英

Set HTTP Body to AFNetworking instead of using native request

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) {
}

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 .

     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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM