标签:
1.新建一个single view工程,导入ASIHttpRequest库,导入MobileCoreServices、CFNetwork、SystemConfiguration和libz1.2.5.dylib四个系统库
2.随便导入一张图片,比如haoyou.png
3.ViewController.h
1
2
3
4
5
6
|
# import <uikit uikit.h= "" > # import "ASIHTTPRequest.h" # import "ASIFormDataRequest.h" @interface ViewController : UIViewController @property (nonatomic, copy)NSString *m_auth; @end </asihttprequestdelegate></uikit> |
4.ViewController.m 添加两个按钮
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
- ( void )viewDidLoad { [ super viewDidLoad]; UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; loginBtn.frame = CGRectMake( 100 , 20 , 120 , 40 ); [loginBtn setTitle:@ "登录" forState:UIControlStateNormal]; [loginBtn addTarget:self action: @selector (login) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:loginBtn]; UIButton *uploadBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; uploadBtn.frame = CGRectMake( 100 , 80 , 120 , 40 ); [uploadBtn setTitle:@ "上传" forState:UIControlStateNormal]; [uploadBtn addTarget:self action: @selector (upload) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:uploadBtn]; } |
5.实现login和upload两个方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
- ( void )login { NSURL *url = [NSURL URLWithString:@ "..." ]; //此处省略请求url //请求 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; request.tag = 10 ; request.delegate = self; [request startAsynchronous]; } - ( void )upload { NSURL* url = [NSURL URLWithString:@ "..." ]; //此处省略请求url UIImage* img = [UIImage imageNamed:@ "haoyou.png" ]; NSData* data = UIImagePNGRepresentation(img); //ASIFormDataRequest请求是post请求,可以查看其源码 ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:url]; request.tag = 20 ; request.delegate = self; [request setPostValue:self.m_auth forKey:@ "m_auth" ]; // [request setFile:@"tabbar.png" forKey:@"haoyou"];//如果有路径,上传文件 [request setData:data withFileName:@ "tmp.png" andContentType:@ "image/png" forKey:@ "headimage" ]; // 数据 文件名,随便起 文件类型 设置key [request startAsynchronous]; } |
6.实现协议
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
- ( void )requestFailed:(ASIHTTPRequest *)request { NSLog(@ "请求失败" ); } - ( void )requestFinished:(ASIHTTPRequest *)request { if (request.tag == 10 ) { NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:request.responseData options: 0 error:nil]; self.m_auth = [dic objectForKey:@ "m_auth" ]; NSLog(@ "%@" , self.m_auth); } if (request.tag == 20 ) { NSLog(@ "%@" , request.responseString); } } |
标签:
原文地址:http://www.cnblogs.com/AnJinming/p/4963106.html