2015-04-06 57 views
0

我正在學習如何使用AFNetworking for iOS。我經常使用ASIHttprequest上傳文件並同時發佈多個參數,使用ASIHttprequest這樣簡單。如何通過AFNetworking上傳文件併發布多個參數?

[request setPostValue:distanceLabel.text forKey:@"km"]; 
[request setPostValue:speedValue forKey:@"speed"]; 
[request setFile:filePath forKey:@"filedata"]; 

我學到了很多關於AFNetworking的知識,但是我不知道該怎麼做。請讓我看看代碼。謝謝!

回答

0

組合一個鍵的多個查詢值。

如果您使用的是NSDictionary + NSSet,您會從NSArray獲得不含[]的查詢網址。

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:[NSSet setWithObjects:@"value1", @"value2", nil], @"myKey", nil]; 

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; 
NSURLRequest *request = [httpClient requestWithMethod:@"GET" path:@"/path" parameters:params]; 

NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; 
NSString *filename = [documentsDirectory stringByAppendingPathComponent:photoName]; 
NSData *imageData = [NSData dataWithContentsOfFile:filename]; 
[formData appendPartWithFileData:imageData 
          name:@"files" 
         fileName:photoName mimeType:@"image/jpeg"]; 
+0

謝謝!該代碼顯示瞭如何在沒有文件的情況下發布多個值。怎麼做? – Donny 2015-04-06 07:55:06

1

嘗試下面的代碼: -

我已經使用這個代碼的圖像。您也可以嘗試其他文件類型。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
NSData *imageData = UIImageJPEGRepresentation(aDict[@"Image"], 0.5); 

AFHTTPRequestOperation *op = [manager POST:aStrURL parameters:aDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
    [formData appendPartWithFileData:imageData name:myParamName fileName:@"photoNew.jpg" mimeType:@"image/jpeg"]; 
} success:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject); 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"Error: %@ ***** %@", operation.responseString, error); 
}]; 
[op start]; 
0

https://github.com/AFNetworking/AFNetworking這裏有着很好的例子, 我如何使用這個東西 1.創建客戶端實例,這將每一次服務的應用程序將需要連接到服務器

file.h

#import "AFHTTPRequestOperationManager.h" 

@interface YourClient : AFHTTPRequestOperationManager 

+ (instancetype)sharedClient; 
- (void)send_Image_POST_WS:(NSString *)ws_name image:(NSData*)imageData param:(NSDictionary *)param :(void (^)(NSDictionary *json, NSError *error, NSInteger status))block; 

file.m

static NSString * const YouBaseURLString = @"http://blablabla"; 
@implementation YourClient 


+ (instancetype)sharedClient { 

    static YourClient *_sharedClient = nil; 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
     _sharedClient = [[YourClient alloc] initWithBaseURL:[NSURL YouBaseURLString]]; 
     _sharedClient.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; 

    }); 

    return _sharedClient; 
} 

// you can change the block according to the needs of its receiver 

- (void)send_Image_POST_WS:(NSString *)ws_name image:(NSData*)imageData param:(NSDictionary*)param :(void (^)(NSDictionary *json, NSError *error, NSInteger status))block{ 

    // NSLog(@「WS: %@\nPARAMS: --> %@",ws_name,[param description]); 

    [self POST:ws_name parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 

     [formData appendPartWithFileData:imageData name:@"imagedata" fileName:@"imagedata.png" mimeType:@"image/png"]; 

    } success:^(AFHTTPRequestOperation *operation, id responseObject) { 

     if (block) { 
      // NSLog(@"WS:%@\nRESPONSE : -> %@",ws_name,responseObject); 
      block(responseObject,nil,operation.response.statusCode); 
     } 

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 

     //NSLog(@"Response error text %@",operation.responseString); 
     // you can display here alert 
     if (block) { 
      block(nil,error,operation.response.statusCode); 
     } 
    }]; 
} 
  • 類,其具有要發送的圖像例如
  • ProfileViewController.m

    -(void)send_UploadImage:(UIImage *)image{ 
    
    // here you can activate a spinner (use which one you want - of Apple or some open source) 
        NSDictionary *params = @{@"extension":@"png", 
              @「usr_id」:@「1」};// <<<—— this is an additional data the service on the server side will need, just example, replace with needed 
    
        NSData *dataImage = UIImageJPEGRepresentation(image, 0.5); 
    // @"common/upload_image" replace with your path to the service on the server side, it will be added to the Base URL 
    
        [[YourClient sharedClient] send_Image_POST_WS:@"common/upload_image" image:dataImage param:params :^(NSDictionary *json, NSError *error) { 
    
         // hide spinner 
    
         if (!error) { 
         // read json, change UI here you are on the main thread  
    
    
         }else{ 
          // react accordingly main thread 
         } 
        }]; 
    } 
    
    相關問題