本人对于AFNetworking理解为利用HTTP协议与服务器互联,本次用AFHTTP往服务器传文件,并解析服务器传回来的json,
首先:在工程里导入AFNetworking框架,
并在需要传文件的类里导入头文件:
#import "AFNetworking.h"
#import "AFHTTPRequestOperation.h"
#import "AFHTTPClient.h"
往服务器传一张图片:
事例:
//将图片转化为NSData类型
NSData *imageData;/
if (image) {
imageData = UIImageJPEGRepresentation(image, 0.5);
}
// NSMutableDictionary * postdata = [[NSMutableDictionary alloc] init];
// [postdata setObject:nil forKey:@"photoUser"];
//上传服务器的地址
NSString * newURL =@"http://mobile.inankai.cn";
//上传图片的接口
NSMutableURLRequest *request = [[AFHTTPClient clientWithBaseURL:[NSURL URLWithString:newURL]] multipartFormRequestWithMethod:@"POST"
//本篇利用POST方法上传图片
path:@"/file/sid/updateUserPhoto/flagTemp/0/" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
//往URL里添加图片(NSData)
[formData appendPartWithFileData:imageData name:@"photoUser" fileName:@"nothing.jpg" mimeType:@"image/jpeg"]; //图片
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
float progress = totalBytesWritten / (float)totalBytesExpectedToWrite;
NSLog(@"Sent %f ..",progress);
}];
//开始上传图片
[operation start];
//上传成功时调用
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//在这里最好打印json,看json 的格式
NSLog(@" imageRequestDidFinish: %@ ",[operation responseString]);
response =[operation responseString];
//对json 进行解析
NSError *error = nil;
NSData *fileIdData = [response dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:fileIdData options:NSJSONReadingMutableLeaves error:&error];
// NSDictionary *dict = [NKNetwork parseDataFromJSON:responseObject];
NSDictionary *dictfil = [dic objectForKey:@"json"];
NSArray* Info =[dictfil objectForKey:@"data"];
NSDictionary * dicfile = [Info objectAtIndex:0];
//解析出来需要上传的fileId
fileIdStr = [dicfile objectForKey:@"fileId"];
NSLog(@"#####resopnse: %@",response);
//上传服务器需要的值
[self updatefileId];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error: %@", operation.responseString);
}];
-(void)updatefileId
{
NSLog(@"fileIdStr:%@",fileIdStr);
//这里我们上传数据采用的时get 方法
//上传服务器所需要的fileID
NSURLRequest *URLRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[NKNetwork updateUserPhotoWithFileId:fileIdStr]]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:URLRequest success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//打印json
[NKTools logJSON:JSON];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
[NKTools logJSON:JSON];
}];
[operation start];
}