How can I set cookies with AFNetworking 2.0 while uploading image with parameters?
Asked Answered
P

1

8

What if I had to attach a cookie with a post request? How should I do this?

NSURL *URL = [NSURL URLWithString:addAddressUrl]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
     
// Set cookie too 
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"<URL>"]]; 
NSDictionary *cookiesDictionary = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies]; 

if(cookiesDictionary) { 
    [request setAllHTTPHeaderFields:cookiesDictionary]; 
}

How to attach this request with AFNetworking call? I have gone through the documents of AFNetworking but it doesn't explain how to set cookie in a request with its manager object.

And if I somehow attach this cookie into afnetworking files internally, still I am not able to upload image. I have tried two possible ways of it:

First way:

-(void)uploadPrescriptionImage :(UIImage *)imagePresc
{
    // upload image here on the prescription
    /*
     Uploading a prescription
     URL: <URL>
     Params: <PARAMS>
     Method: POST
     */
    
    
    NSData *imageData = UIImageJPEGRepresentation(imagePresc, 1.0);
    
    NSString *orderID = [[NSUserDefaults standardUserDefaults] valueForKey:@"orderId"]; // orderId
    
    NSDictionary *parameters = @{@"docName":prescriptionCell.doctorNameTextField.text,@"patientName":prescriptionCell.patientNameTextField.text,@"orderId" : orderID};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:@"<URL>" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {
        [formData appendPartWithFileData:imageData name:@"prescription" fileName:@"prescription" mimeType:@"image/jpeg"];
    }
          success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSLog(@"response is :  %@",responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        NSLog(@"Error: %@ *****", [error description]);
    }];
}

I have attached cookie in afnetworking method like below :

- (AFHTTPRequestOperation *)POST:(NSString *)URLString
                      parameters:(NSDictionary *)parameters
       constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
                         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block];
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"<URL>"]];
    NSDictionary *cookiesDictionary = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
    if (cookiesDictionary) {
        [request setAllHTTPHeaderFields:cookiesDictionary];
    }
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [self.operationQueue addOperation:operation];

    return operation;
}

Second way :

    NSDictionary *parameters = @{@"docName":@"rr",@"patientName":@"tt",@"orderId" : @"1"};
    
    
    NSString *URLString = @"<URL>";
//
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
//
    NSURL *URL = [NSURL URLWithString:URLString];
    NSMutableURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    // Set cookie too
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"<URL>"]];
    NSDictionary *cookiesDictionary = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
    if (cookiesDictionary) {
        [request setAllHTTPHeaderFields:cookiesDictionary];
    }
//
//    NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:[NSURL URLWithString:filePathOfImage] progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error)
    {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            NSLog(@"Success: %@ %@", response, responseObject);
        }
    }];
    [uploadTask resume];
}

But I don't know how to add parameters with this request. I prefer the second way.

Pup answered 25/11, 2013 at 13:43 Comment(0)
P
1

Was able to solve it..I have used it with only first way .. may be that can be used in both the ways :

Here is my code of how i was able to upload an image with afnetworking 2.0 :

NSString *fileName = [NSString stringWithFormat:@"Prescription%d.jpg", counter];

    NSData *imageData = UIImageJPEGRepresentation(imagePresc, 1.0);

    NSString *orderID = [[NSUserDefaults standardUserDefaults] valueForKey:@"orderId"]; // orderId

    NSDictionary *parameters = @{@"docName":prescriptionCell.doctorNameTextField.text,@"patientName":prescriptionCell.patientNameTextField.text,@"orderId" : orderID};

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:@"http://staging.healthkartplus.com/webservices/prescription/upload" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];

    }success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSLog(@"response is :  %@",responseObject);
     }failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Error: %@ *****", [error description]);
     }];

The important part of this code is :

[formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];

Here in above line of code you need to specify exactly the name of the parameter and the type of the parameter (image). Here the "file" parameter must be passed to it (according to API which i got from my server side guys) and the type should be "image/jpeg"(or image/pdf or i think image/png). and you can pass any name for the fileName, here i am passing file name as : NSString *fileName = [NSString stringWithFormat:@"Prescription%d.jpg", counter];

The only mistake i was doing is i was not specifying correct parameter for image , to summerise i should have sent it like :

  • parameter key : "file"
  • data : "file or image data"
  • filename : ".jpg" // NOTE : extension of image name must be there
  • mime type : ""
Pup answered 10/12, 2013 at 11:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.