如何在上传带有参数的图像时使用 AFNetworking 2.0 设置 cookie? [英] How can I set cookies with AFNetworking 2.0 while uploading image with parameters?

查看:30
本文介绍了如何在上传带有参数的图像时使用 AFNetworking 2.0 设置 cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我必须在发布请求中附加一个 cookie 怎么办?我该怎么做?

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]; 
}

如何通过 AFNetworking 调用附加此请求?我已经阅读了 AFNetworking 的文档,但它没有解释如何在请求中使用它的管理器对象设置 cookie.

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.

如果我以某种方式将此 cookie 附加到内部网络文件中,我仍然无法上传图像.我已经尝试了两种可能的方法:

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:

第一种方式:

-(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]);
    }];
}

我已经在如下的网络方法中附加了 cookie:

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;
}

第二种方式:

    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.

推荐答案

能够解决它..我只用第一种方式..可能两种方式都可以使用:

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

这是我如何使用 afnetworking 2.0 上传图像的代码:

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"];

在上面的代码行中,您需要准确指定参数的名称和参数的类型(图像).这里必须将文件"参数传递给它(根据我从服务器端人员那里获得的 API),并且类型应该是图像/jpeg"(或图像/pdf 或我认为是图像/png).并且您可以为文件名传递任何名称,这里我将文件名传递为:NSString *fileName = [NSString stringWithFormat:@"Prescription%d.jpg", counter];

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 :

  • 参数键:文件"
  • 数据:文件或图像数据"
  • filename : ".jpg"//注意:扩展名图像名称必须存在
  • mime 类型:""

这篇关于如何在上传带有参数的图像时使用 AFNetworking 2.0 设置 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆