您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 檔案上傳實作:用 AFNetworking 上傳圖片到伺服器

編輯:iOS 相關資訊

幾乎每個 App 都有上傳需求——頭像、身分證件、聊天圖片。以下以 AFNetworking 為例,示範完整的 multipart 檔案上傳流程,並額外示範 UIPickerView 讓使用者挑選要上傳的檔案。

第一步:在 AppDelegate 建立共用的 manager

#import <UIKit/UIKit.h>
#import "AFHTTPRequestOperationManager.h"

@interface FKAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) AFHTTPRequestOperationManager *manager;

@end
#import "FKAppDelegate.h"

@implementation FKAppDelegate

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.manager = [AFHTTPRequestOperationManager manager];
    self.manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
    return YES;
}

@end

把 manager 放在 AppDelegate 的好處是全 App 共用一個連線設定(逾時、快取原則、驗證憑證等),不必每個頁面各自建立。

第二步:建立檔案選擇器

在 ViewController 中用 UIPickerView 呈現可選的檔案清單:

#import "FKViewController.h"
#import "FKAppDelegate.h"

@interface FKViewController ()
{
    FKAppDelegate *appDelegate;
    NSArray *images;
}
@end

@implementation FKViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    appDelegate = [UIApplication sharedApplication].delegate;
    self.picker.dataSource = self;
    self.picker.delegate = self;

    images = @[@"logo", @"java", @"android"];
}

// UIPickerViewDataSource:決定有幾欄
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView
 numberOfRowsInComponent:(NSInteger)component
{
    return images.count;
}

#define kImageTag 1

// 自訂每一列的檢視
- (UIView *)pickerView:(UIPickerView *)pickerView
            viewForRow:(NSInteger)row
          forComponent:(NSInteger)component
       reusingView:(UIView *)view
{
    // 若可重用的 view 沒有我們的 tag,表示這是系統預建的佔位 view,需重新配置
    if (view.tag != kImageTag)
    {
        view = [[UIView alloc] init];
        view.tag = kImageTag;
        view.userInteractionEnabled = NO;

        UIImageView *iv = [[UIImageView alloc]
            initWithImage:[UIImage imageNamed:[images objectAtIndex:row]]];
        iv.frame = CGRectMake(0, 0, 48, 48);
        iv.contentMode = UIViewContentModeScaleAspectFit;
        [view addSubview:iv];
    }
    return view;
}

// UIPickerViewDelegate:列高
- (CGFloat)pickerView:(UIPickerView *)pickerView
rowHeightForComponent:(NSInteger)component
{
    return 48;
}

// 列寬
- (CGFloat)pickerView:(UIPickerView *)pickerView
   widthForComponent:(NSInteger)component
{
    return 48;
}

這裡用 tag 判斷是否為自己配置過的 view,是因為 reusingView 參數第一次傳入時會是系統準備的容器而非 nil,若不判斷就會把子檢視不斷疊上去。

第三步:執行上傳

- (IBAction)upload:(id)sender
{
    // 取得使用者選取的列
    NSInteger selectedRow = [self.picker selectedRowInComponent:0];
    NSString *fileName = [images objectAtIndex:selectedRow];

    // 依檔名定位到 bundle 中的資源
    NSURL *filePath = [[NSBundle mainBundle] URLForResource:fileName
                                            withExtension:@"png"];

    NSDictionary *parameters = @{@"name": @"額外的請求參數"};

    [appDelegate.manager POST:@"https://192.168.1.88:8888/AFNetworkingServer/upload"
                   parameters:parameters
    constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
    {
        [formData appendPartWithFileURL:filePath
                                   name:@"file"          // 對應後端接收的欄位名
                               fileName:[NSString stringWithFormat:@"%@.png", fileName]
                               mimeType:@"image/png"
                                  error:nil];
    }
                      success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        // responseSerializer 設為 AFHTTPResponseSerializer 時,回應是 NSData
        NSString *result = [[NSString alloc] initWithData:responseObject
                                                encoding:NSUTF8StringEncoding];
        [[[UIAlertView alloc] initWithTitle:@"上傳結果"
                                    message:result
                                   delegate:self
                          cancelButtonTitle:@"確定"
                          otherButtonTitles:nil] show];
    }
                      failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        NSLog(@"獲取服務器響應出錯!%@", error);
    }];
}

@end

關鍵概念說明

constructingBodyWithBlock 是整個上傳的核心。它讓你在 block 中組裝 multipart/form-data 的內容,appendPartWithFileURL:name:fileName:mimeType:error: 的四個參數分別對應:檔案本體、後端程式讀取的欄位名稱、原始檔名、以及 MIME 類型。這三者若與後端約定不一致,就會出現「伺服器收到空檔」的狀況。

responseSerializer 的選擇會影響 success block 中 responseObject 的型別。設為 AFHTTPResponseSerializer 時拿到的是原始 NSData,需要自己轉字串;若改用 AFJSONResponseSerializer,則會直接得到已解析的 NSDictionary,處理起來更省事。

實務上的補充建議

第一,加上進度回報。AFNetworking 的上傳操作提供 uploadProgress 的監聽,透過 KVO 觀察 operation.uploadProgress 的 fractionCompleted 就能更新進度條,使用者體驗差距很大。

第二,加上錯誤處理與重試。網路不穩時上傳失敗很常見,failure block 中至少要把 error.localizedDescription 呈現給使用者,並提供重試入口。

第三,圖片壓縮。上傳前先用 UIImageJPEGRepresentation(image, 0.7) 之類的方式壓縮,能顯著降低流量與上傳時間。

第四,關於版本。範例使用的是 AFNetworking 2.x 的 AFHTTPRequestOperationManager,在 3.x 之後已改為 AFHTTPSessionManager,寫法略有不同(改用 dataTaskWithRequest:uploadProgress:completionHandler:)。若你在新專案中實作,建議直接採用 SessionManager 版本,並注意 AFNetworking 已進入維護模式,新專案可考慮改用 URLSession 原生 API。

最後,範例中的伺服器位址是區網 IP,實際部署時記得改用正式網域並優先採用 HTTPS——上傳身分證件、醫療文件這類敏感資料時,明文 HTTP 傳輸是不合格的。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved