0.導(dǎo)入框架準(zhǔn)備工作
1. 將框架程序拖拽進(jìn)項(xiàng)目
2. 添加iOS框架引用
–SystemConfiguration.framework–MobileCoreServices.framework
3. 引入
#import "AFNetworking.h"
4. 修改xxx-Prefix.pch文件
#import <MobileCoreServices/MobileCoreServices.h>#import <SystemConfiguration/SystemConfiguration.h>
1.AFN的客戶端,使用基本地址初始化,同時(shí)會(huì)實(shí)例化一個(gè)操作隊(duì)列,以便于后續(xù)的多線程處理
@interfaceViewController (){ // AFN的客戶端,使用基本地址初始化,同時(shí)會(huì)實(shí)例化一個(gè)操作隊(duì)列,以便于后續(xù)的多線程處理 AFHTTPClient *_httpClient; NSOperationQueue *_queue;}- (void)viewDidLoad{ [super viewDidLoad]; NSURL *url = [NSURL URLWithString:@"http://192.168.3.255/~apple/qingche"]; _httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; _queue = [[NSOperationQueue alloc] init];}2.利用AFN實(shí)現(xiàn)文件上傳操作細(xì)節(jié)
#pragma mark - 文件上傳- (IBAction)uploadImage{ /* 此段代碼如果需要修改,可以調(diào)整的位置 1. 把upload.php改成網(wǎng)站開(kāi)發(fā)人員告知的地址 2. 把file改成網(wǎng)站開(kāi)發(fā)人員告知的字段名 */ // 1. httpClient->url // 2. 上傳請(qǐng)求POST NSURLRequest *request = [_httpClient multipartFormRequestWithMethod:@"POST" path:@"upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { // 在此位置生成一個(gè)要上傳的數(shù)據(jù)體 // form對(duì)應(yīng)的是html文件中的表單 UIImage *image = [UIImage imageNamed:@"頭像1"]; NSData *data = UIImagePNGRepresentation(image); // 在網(wǎng)絡(luò)開(kāi)發(fā)中,上傳文件時(shí),是文件不允許被覆蓋,文件重名 // 要解決此問(wèn)題, // 可以在上傳時(shí)使用當(dāng)前的系統(tǒng)事件作為文件名 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; // 設(shè)置時(shí)間格式 formatter.dateFormat = @"yyyyMMddHHmmss"; NSString *str = [formatter stringFromDate:[NSDate date]]; NSString *fileName = [NSString stringWithFormat:@"%@.png", str]; /* 此方法參數(shù) 1. 要上傳的[二進(jìn)制數(shù)據(jù)] 2. 對(duì)應(yīng)網(wǎng)站上[upload.php中]處理文件的[字段"file"] 3. 要保存在服務(wù)器上的[文件名] 4. 上傳文件的[mimeType] */ [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"]; }]; // 3. operation包裝的urlconnetion AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request]; [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"上傳完成"); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"上傳失敗->%@", error); }]; //執(zhí)行 [_httpClient.operationQueue addOperation:op];以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注