官方建議AFN的使用方法
1. 定義一個(gè)全局的AFHttpClient:包含有
1> baseURL
2> 請(qǐng)求
3> 操作隊(duì)列 NSOperationQueue
2. 由AFHTTPRequestOperation負(fù)責(zé)所有的網(wǎng)絡(luò)操作請(qǐng)求
#import "AFNetworking.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <SystemConfiguration/SystemConfiguration.h>
1 @interfaceViewController () 2 3 { 4 5 // AFN的客戶端,使用基本地址初始化,同時(shí)會(huì)實(shí)例化一個(gè)操作隊(duì)列,以便于后續(xù)的多線程處理 6 7 AFHTTPClient *_httpClient;17 NSOperationQueue *_queue;18 19 }
1 - (void)viewDidLoad2 {3 [super viewDidLoad];4 5 NSURL *url = [NSURL URLWithString:@"http://192.168.3.255/~apple/qingche"];6 _httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];7 8 _queue = [[NSOperationQueue alloc] init];9 }
1 #pragma mark - 文件上傳 2 - (IBAction)uploadImage 3 { 4 /* 5 此段代碼如果需要修改,可以調(diào)整的位置 6 7 1. 把upload.php改成網(wǎng)站開發(fā)人員告知的地址 8 2. 把file改成網(wǎng)站開發(fā)人員告知的字段名 9 */10 // 1. httpClient->url11 12 // 2. 上傳請(qǐng)求POST13 NSURLRequest *request = [_httpClient multipartFormRequestWithMethod:@"POST" path:@"upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {14 // 在此位置生成一個(gè)要上傳的數(shù)據(jù)體15 // form對(duì)應(yīng)的是html文件中的表單16 17 18 UIImage *image = [UIImage imageNamed:@"頭像1"];19 NSData *data = UIImagePNGRepresentation(image);20 21 // 在網(wǎng)絡(luò)開發(fā)中,上傳文件時(shí),是文件不允許被覆蓋,文件重名22 // 要解決此問題,23 // 可以在上傳時(shí)使用當(dāng)前的系統(tǒng)事件作為文件名24 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];25 // 設(shè)置時(shí)間格式26 formatter.dateFormat = @"yyyyMMddHHmmss";27 NSString *str = [formatter stringFromDate:[NSDate date]];28 NSString *fileName = [NSString stringWithFormat:@"%@.png", str];29 30 31 /*32 此方法參數(shù)33 1. 要上傳的[二進(jìn)制數(shù)據(jù)]34 2. 對(duì)應(yīng)網(wǎng)站上[upload.php中]處理文件的[字段"file"]35 3. 要保存在服務(wù)器上的[文件名]36 4. 上傳文件的[mimeType]37 */38 [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];39 }];40 41 // 3. operation包裝的urlconnetion42 AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];43 44 [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responSEObject) {45 NSLog(@"上傳完成");46 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {47 NSLog(@"上傳失敗->%@", error);48 }];49 50 //執(zhí)行51 [_httpClient.operationQueue addOperation:op];
作者: 清澈Saup
出處: http://www.survivalescaperooms.com/qingche/
本文版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但必須保留此段聲明,且在文章頁面明顯位置給出原文連接。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注