在使用参数上传图片时,如何使用AFNetworking 2.0设置Cookie? [英] How can I set cookies with AFNetworking 2.0 while uploading image with parameteres?

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

问题描述

如果我必须附加带有帖子请求的Cookie,该怎么办?我应该怎么做?

What if I had to attach a cookie with a post requst? 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.

和iF我有一些将此cookie附加到网络文件内部,仍然我不能上传图像。我尝试过两种可能的方法:

And iF i some how 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 atttached 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 dont know how do i add parameters with this request .. common Matt Thompson .. Please help me this is making frushtrated everyone .. I would like to prefer 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]);
     }];

此代码的重要部分是:

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

在上面的代码行中,需要准确指定参数的名称和类型参数(图像)。这里的文件参数必须传递给它(根据API,我从我的服务器端家伙),类型应该是image / jpeg(或者image / pdf或i think image / png)。你可以传递fileName的任何名称,这里我传递文件名为: 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 :


  • 参数键:file

  • data:file or image data

  • filename :.jpg//注意:
    图片名称的扩展名必须为

  • mime type:

  • parameter key : "file"
  • data : "file or image data"
  • filename : ".jpg" // NOTE : extension of image name must be there
  • mime type : ""

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

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