iOS用ASIHttpRequest上傳
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 </pre>
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]; } </pre>
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]; } </pre>
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); } } </pre>
本文由用戶 ccwv 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!