1.建立一個single view工程,匯入ASIHttpRequest庫,匯入MobileCoreServices、CFNetwork、SystemConfiguration和libz1.2.5.dylib四個系統庫
2.隨便匯入一張圖片,比如haoyou.png
3.ViewController.h
#import #import "ASIHTTPRequest.h"#import "ASIFormDataRequest.h"@interface ViewController : UIViewController @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); }}