1. Create a single View project, import the ASIHTTPRequest library, import the Mobilecoreservices, Cfnetwork, SystemConfiguration, and libz1.2.5.dylib four system libraries
2. Randomly import a picture, such as 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 Add two buttons
?
| 1 2 3 4 5 6 7 8 9 Ten One A - - the |
- (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. Two ways to implement login and upload
?
| 1 2 3 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. Implementing the Agreement
?
| 1 2 3 4 5 6 7 8 9 Ten One A - - |
- (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); }} |
iOS uploads with ASIHTTPRequest