iOS用ASIHttpRequest上传
2018-07-20 来源:open-open
1.新建一个single view工程,导入ASIHttpRequest库,导入MobileCoreServices、CFNetwork、SystemConfiguration和libz1.2.5.dylib四个系统库
2.随便导入一张图片,比如haoyou.png
3.ViewController.h
#import <UIKit/UIKit.h> #import "ASIHTTPRequest.h" #import "ASIFormDataRequest.h" @interface ViewController : UIViewController <ASIHTTPRequestDelegate> @property (nonatomic, copy)NSString *m_auth; @end
4.ViewController.m 添加两个按钮
- (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两个方法
- (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.实现协议
- (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); } }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇:python根据域名获得ip地址
下一篇:C++算法之字符串查找
最新资讯
热门推荐