iOS- 利用AFNetworking(AFN) - 實現圖片上傳

來源:互聯網
上載者:User

標籤:

iOS- 利用AFNetworking(AFN) - 實現圖片上傳  

 官方建議AFN的使用方法

 1. 定義一個全域的AFHttpClient:包含有

    1> baseURL

    2> 請求

    3> 操作隊列 NSOperationQueue

 2. 由AFHTTPRequestOperation(HTTP請求操作)負責所有的網路操作請求

 3. 修改xxx-Prefix.pch檔案

#import <MobileCoreServices/MobileCoreServices.h>

#import <SystemConfiguration/SystemConfiguration.h>

0.匯入架構準備工作

•1. 將架構程式拖拽進項目

•2.  添加iOS架構引用

–SystemConfiguration.framework

–MobileCoreServices.framework

•3.  引入

#import "AFNetworking.h"

1.AFN的用戶端,使用基本地址初始化,同時會執行個體化一個操作隊列,以便於後續的多執行緒 2.利用AFN實現檔案上傳操作細 1 #pragma mark - 檔案上傳
 2 - (IBAction)uploadImage 3 { 4     /* 5      此段代碼如果需要修改,可以調整的位置 6       7      1. 把upload.php改成網站開發人員告知的地址 8      2. 把file改成網站開發人員告知的欄位名 9      */10     // 1. httpClient -> url11     // AFN的用戶端,使用基本地址初始化,同時會執行個體化一個操作隊列,以便於後續的多執行緒
5     NSURL *url = [NSURL URLWithString:@"http://192.168.3.255/~apple/qingche"];6     AFHTTPClient *_httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
  NSOperationQueue *_queue = [[NSOperationQueue alloc] init];
12 // 2. 上傳請求POST 13 NSURLRequest *request = [_httpClient multipartFormRequestWithMethod:@"POST" path:@"upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 14 // 在此位置產生一個要上傳的資料體,form對應的是html檔案中的表單 18 UIImage *image = [UIImage imageNamed:@"頭像1"]; 19 NSData *data = UIImagePNGRepresentation(image); 21 // 在網路開發中,上傳檔案時,是檔案不允許被覆蓋,檔案重名,要解決此問題, 可以在上傳時使用當前的系統事件作為檔案名稱 24 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 25 // 設定時間格式 26 formatter.dateFormat = @"yyyyMMddHHmmss"; 27 NSString *str = [formatter stringFromDate:[NSDate date]]; 28 NSString *fileName = [NSString stringWithFormat:@"%@.png", str]; 31 /* 32 此方法參數 33 1. 要上傳的[位元據] 34 2. 對應網站上[upload.php中]處理檔案的[欄位"file"] 35 3. 要儲存在伺服器上的[檔案名稱] 36 4. 上傳檔案的[mimeType] 37 */ 
[formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];39 }];41 // 3. operation(HTTP請求操作)封裝的urlconnetion42 AFHTTPRequestOperation *httpROpe = [[AFHTTPRequestOperation alloc] initWithRequest:request];44 [httpROpe setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {45 NSLog(@"上傳完成");46 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {47 NSLog(@"上傳失敗->%@", error);48 }];50 //執行51 [_httpClient.operationQueue addOperation:op];
 

iOS- 利用AFNetworking(AFN) - 實現圖片上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.