2016-04-04 66 views
0

我想發送一個發佈請求到我的後端,包含一些數據和UIImage作爲NSData對象。問題是,我不知道如何使用AFNetworking 3.0。AFNetworking 3.x數據和圖像發佈請求

我迄今爲止代碼:

NSString *url = [NSString stringWithFormat:@"%@%@", baseURL, @"/postProjectNote"]; 

NSMutableDictionary *dic = [[NSMutableDictionary alloc]init]; 

[dic setObject:session forKey:@"session"]; 
[dic setObject:timestamp forKey:@"timestamp"]; 
[dic setObject:project_id forKey:@"project_id"]; 
[dic setObject:type forKey:@"type"]; 

NSData imagedata = UIImageJPEGRepresentation(myUIImage, 0.8); 

我不需要任何形式的進度條。如果請求成功或者不成功,我只需要一個結果。後端(Laravel 5)給了我一個json字符串。我需要發送表單數據。

你能幫我開始嗎?

回答

2

使用此代碼使用後的圖像AFNetworking:

AFHTTPRequestOperationManager* manager = [[AFHTTPRequestOperationManager alloc] init]; 
manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 
manager.requestSerializer = [AFJSONRequestSerializer serializer]; 
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"]; 

NSData *imageData = UIImageJPEGRepresentation(image, 0.5); 
NSMutableDictionary *paramDict = [NSMutableDictionary new]; // Add additional parameters here 
AFHTTPRequestOperation *op = [manager POST:UPDATE_PROFILE_IMAGE parameters:paramDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
    [formData appendPartWithFileData:imageData name:@"file" fileName:@"filename" mimeType:@"image/jpeg"]; 
} success:^(AFHTTPRequestOperation *operation, id responseObject) { 
    if (success) { 
     // Success 
    } 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    // Failure 
}]; 
[op start]; 
+0

這適用於AFNetworking 2.X不3.x的但使用遷移教程很容易進行轉換。 – Dafen

0
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);  
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 
    manager.responseSerializer = [AFJSONResponseSerializer serializer]; 
    [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"]; 
    [manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; 
    manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"text/html",@"application/json",nil]; 

    [manager POST:encoded parameters:"the params you want to pass" constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { 
    [formData appendPartWithFileData:imageData 
           name:"image name with timestamp" 
          fileName:@"image_upload_file" 
          mimeType:[NSString mimeTypeForImageData:data]]; 
} progress:^(NSProgress * _Nonnull uploadProgress) { 
    //DLog(@"Progress = %@",uploadProgress); 
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { 
    //DLog(@"Response = %@",responseObject); 
    completion(YES,responseObject,nil); 
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { 
    completion(NO,nil,error); 
    //DLog(@"Error: %@", error); 
}];