在使用参数上传图像时,如何使用AFNetworking 2.0设置cookie?

时间:2013-11-25 13:43:21

标签: ios afnetworking-2

如果我必须附上一个带有后期要求的cookie,该怎么办?我该怎么做?

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。

我知道如何在内部将此cookie附加到afnetworking文件中,仍然无法上传图像。我尝试过两种可能的方法:

第一种方式:

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

我已经在下面的afnetworking方法中添加了cookie:

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

但是我不知道如何用这个请求添加参数..常见的Matt Thompson ..请帮助我这让每个人都感到沮丧..我想更喜欢第二种方式..

1 个答案:

答案 0 :(得分:1)

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

以下是我如何使用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"];

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

我唯一的错误是我没有为图像指定正确的参数,夏天我应该发送它像:

  • 参数键:“file”
  • 数据:“文件或图像数据”
  • filename:“.jpg”//注意:扩展名 图像名称必须在那里
  • mime type:“”