您的位置:首页 > 理论基础 > 计算机网络

iOS开发 ----- 网络请求3 ----- 上传数据

2015-09-26 18:57 621 查看

上传数据

系列导航

网络请求1 —> 概览

网络请求2 —> 请求数据

网络请求3 —> 上传数据

网络请求4 —> 下载数据以及断点续传

本来想自己写的,不用第三方框架,结果要拼接HTTP请求头部信息,真是难为人啊,这TM根本没听说过啊,翻了几个Blog结果写的都不是很清楚,很蛋疼,不知道怎么弄,等有时间在研究下把 现在写好了,上传图片传送门

这个是用AFNetWorking写的上传,凑合着看吧,等吧HTTPheader的那个搞定之后,在写一篇,真正自己实现上传数据

#import "ViewController.h"
#import "AFNetworking.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

[self login];

UIButton * buton = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
buton.backgroundColor = [UIColor redColor];
[buton addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:buton];

}
-(void)click
{
NSLog(@"click");
[self upload2];
}

//登陆
-(void)login
{
//上传地址
NSString * path = @"http://10.0.8.8/sns/my/login.php?username=kael8&password=123123123";
//转为URL
NSURL * url = [NSURL URLWithString:path];
//初始化请求
NSMutableURLRequest * reuqest = [NSMutableURLRequest requestWithURL:url];
//设置请求方式
reuqest.HTTPMethod = @"POST";
//初始化session的配置
NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
//初始化session
NSURLSession * session = [NSURLSession sessionWithConfiguration:config];

NSURLSessionDataTask * task = [session dataTaskWithRequest:reuqest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"login : %@",response);

NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"login : %@",[dict objectForKey:@"message"]);

}];

//启动上传
[task resume];

}

//上传函数
-(void)upload2
{
NSString * path = @"http://10.0.8.8/sns/my/upload_headimage.php";
//初始化manager
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
//设置为data响应器
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//开始上传
[manager POST:path parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//拼接数据
UIImage * image = [UIImage imageNamed:@"10_7.jpg"];
NSData * data = UIImageJPEGRepresentation(image, 1.0);
[formData appendPartWithFileData:data name:@"headimage" fileName:@"10_7.jpg" mimeType:@"image/jpeg"];

} success:^(AFHTTPRequestOperation *operation, id responseObject) {
//成功时候打印
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];

NSLog(@"%@",dict);
NSLog(@"%@",[dict objectForKey:@"message"]);
NSLog(@"%@",operation);

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

NSLog(@"%@",error);
}];

}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: