o(╯□╰)o好忙,那个,一般公司里面都是用自己封装的网络请求来进行网络数据的交互
但不包括一些小项目,封装一个就麻烦多了直接github下载afnetworking
然后:具体如下
1.上传头像使用
//把图片写入文件(沙盒)
// 此处为截取的图片(截取的图片没有名字,只有数据对象,所以写到文件里面)
NSData * imagedata=UIImagePNGRepresentation(pushimage);
NSArray * paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString * documentsDirectory = [pathsobjectAtIndex:0];
// 在沙盒里把数据存储为实体对象
NSString * savedImagePath=[documentsDirectorystringByAppendingPathComponent:@"saveFore.png"];
[imagedata writeToFile:savedImagePathatomically:YES];
// 读取文件内容
NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)lastObject];
NSString *path=[docPathstringByAppendingPathComponent:@"saveFore.png"];
// 这是路径 ,取文件使用
NSLog(@"path=%@",path);
// 开始使用AFN
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManagermanager];
// 下面这段话必须写,这是内容类型,不写会上传失败
manager.responseSerializer.acceptableContentTypes = [NSSetsetWithObject:@"text/html"];//设置相应内容类型
//用一个imageview对象接受文件
UIImage *savedImage = [[UIImagealloc] initWithContentsOfFile:path];
// 然后就开始了,把你的接口弄过来
[manager POST:@"http://www.123.com"parameters:nilconstructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:UIImagePNGRepresentation(savedImage)
name:@"service_sort_graphic"
fileName:path
mimeType:@"image/png"];
} success:^(AFHTTPRequestOperation *operation,id responseObject) {
如果成功就打印这个
NSLog(@"Success== %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
如果失败就打印这个
NSLog(@"Error: %@", error);
}];
2.上传现有图片
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
// 下面这段话必须写,这是内容类型,不写会上传失败
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];//设置相应内容类型
//用一个imageview对象接受文件
UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:path];
// 然后就开始了,把你的接口弄过来
[manager POST:@"http://www.123.com" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:UIImagePNGRepresentation(savedImage)
name:@"service_sort_graphic"
fileName:path
mimeType:@"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
如果成功就打印这个
NSLog(@"Success== %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
如果失败就打印这个
NSLog(@"Error: %@", error);
}];