當 App 需要在多處、隨時上傳資料,並要求「App 被殺掉後任務不遺失」,就不能只在記憶體裡管任務了。本文示範一個結合 FMDB 持久化與 NSOperationQueue 併發的上傳管理器,分五個部分完成。

以 CocoaPods 管理依賴。在終端機進入專案目錄後執行:
pod init
這會產生一個 Podfile,在 target 中加入 FMDB:
target 'UploadManager' do
pod 'FMDB', '2.5'
end
target 'UploadManagerTests' do
end
回到終端安裝:
pod install
看到類似下面的輸出即完成,此後請改用 UploadManager.xcworkspace 開啟專案:
Analyzing dependencies Downloading dependencies Installing FMDB (2.5) Generating Pods project Integrating client project
整體採用「請求佇列 + 進行中字典」的經典結構:PendingOperations 負責保存待辦與進行中的任務以及 NSOperationQueue;MerchantTask 繼承 NSOperation 負責實際執行;透過 MerchantTaskDelegate 協定把進度回報給 UI。
PendingOperations.h
@interface PendingOperations : NSObject @property (nonatomic, strong) NSMutableDictionary *uploadInProgress; @property (nonatomic, strong) NSMutableDictionary *uploadFinishProgress; @property (nonatomic, strong) NSOperationQueue *uploadQueue; @end
PendingOperations.m
@implementation PendingOperations
- (NSMutableDictionary *)uploadInProgress {
if (!_uploadInProgress) {
_uploadInProgress = [[NSMutableDictionary alloc] init];
}
return _uploadInProgress;
}
- (NSOperationQueue *)uploadQueue {
if (!_uploadQueue) {
_uploadQueue = [[NSOperationQueue alloc] init];
_uploadQueue.name = @"Upload Queue";
_uploadQueue.maxConcurrentOperationCount = 4; // 最多 4 個併發
}
return _uploadQueue;
}
@end
MerchantTask.h:定義任務與回呼協定。
@protocol MerchantTaskDelegate;
@interface MerchantTask : NSOperation
@property (nonatomic, assign) id<MerchantTaskDelegate> delegate;
@property (nonatomic, readonly, strong) NSIndexPath *indexPathInTableView;
@property (nonatomic, readonly, strong) UploadTable *taskRecord;
- (id)initWithTaskRecord:(UploadTable *)record
atIndexPath:(NSIndexPath *)indexPath
delegate:(id<MerchantTaskDelegate>)theDelegate;
- (NSString *)uploadText:(NSString *)textUrl withText:(NSString *)text;
- (NSString *)uploadPic:(NSString *)picUrl widthPicText:(NSString *)picText;
- (NSString *)sysPicInfo:(NSString *)sysUrl withSysText:(NSString *)sysText;
@end
@protocol MerchantTaskDelegate <NSObject>
// 回傳整個 operation 物件,讓呼叫方同時取得 index 與任務記錄
- (void)merchantTaskDidFinish:(MerchantTask *)uploader;
@end
MerchantTask.m:重點在 main 方法中的進度回報方式。
@interface MerchantTask ()
@property (nonatomic, readwrite, strong) NSIndexPath *indexPathInTableView;
@property (nonatomic, readwrite, strong) UploadTable *taskRecord;
@end
@implementation MerchantTask
- (id)initWithTaskRecord:(UploadTable *)record
atIndexPath:(NSIndexPath *)indexPath
delegate:(id<MerchantTaskDelegate>)theDelegate {
if (self = [super init]) {
self.delegate = theDelegate;
self.indexPathInTableView = indexPath;
_taskRecord = record;
}
return self;
}
- (void)main {
@autoreleasepool {
_taskRecord.starting = TRUE;
[self uploadText:@"https://www.example.com" withText:@"內容"];
}
}
// 狀態碼:0 未處理 1 文字上傳中 2 文字上傳失敗 3 圖片未上傳
// 4 圖片上傳中 5 圖片上傳失敗 6 圖片同步中 7 圖片同步失敗 8 完成
- (NSString *)uploadText:(NSString *)textUrl withText:(NSString *)text {
_taskRecord.upload_progress = 1;
_taskRecord.upload_status = 0;
[self notifyDelegate];
// 假裝上傳文字
usleep(1000 * 1000);
[self uploadPic:@"https://www.example.com/pic" widthPicText:@"上傳圖片"];
return @"";
}
- (NSString *)uploadPic:(NSString *)picUrl widthPicText:(NSString *)picText {
// 以 -1 搭配 upload_show_text 呈現百分比進度
int progresses[] = {10, 30, 70, 100};
for (int i = 0; i < 4; i++) {
_taskRecord.upload_progress = -1;
_taskRecord.upload_status = 1;
_taskRecord.upload_show_text =
[NSString stringWithFormat:@"%d %%", progresses[i]];
[self notifyDelegate];
usleep(1000 * 1000);
}
_taskRecord.upload_progress = -1;
_taskRecord.upload_status = 2;
_taskRecord.upload_show_text = @"100 %";
[self notifyDelegate];
[self sysPicInfo:@"" withSysText:@""];
return @"";
}
- (NSString *)sysPicInfo:(NSString *)sysUrl withSysText:(NSString *)sysText {
_taskRecord.upload_progress = 6;
_taskRecord.upload_status = 2;
[self notifyDelegate];
usleep(1000 * 5000);
_taskRecord.upload_progress = 8;
_taskRecord.upload_status = 3;
[self notifyDelegate];
return @"";
}
// 統一的通知入口:切回主線程更新 UI
- (void)notifyDelegate {
[(NSObject *)self.delegate
performSelectorOnMainThread:@selector(merchantTaskDidFinish:)
withObject:self
waitUntilDone:NO];
}
@end
上面的 usleep 只是用來模擬耗時,實際上傳請替換為 AFNetworking 或 NSURLSession 的請求,並在 upload progress 回呼中更新進度。
UploadTable.h:任務記錄的資料模型。
@interface UploadTable : NSObject
@property (nonatomic, strong) NSString *upload_id; // 協議/工單/臨時工單 ID
@property (nonatomic, strong) NSString *upload_name; // 商戶名稱
@property (nonatomic, strong) NSString *upload_type; // 0 協議 1 工單 2 臨時工單
@property (nonatomic, strong) NSString *upload_text; // 文字資訊(JSON)
@property (nonatomic, strong) NSString *upload_img_name; // 圖片名稱(JSON)
@property (nonatomic, strong) NSString *upload_img_sys; // 圖片同步資料
@property int upload_progress; // UI 用:0 未處理 1 文字中 2 文字失敗 3 圖片未傳
// 4 圖片中 5 圖片失敗 6 同步中 7 同步失敗 8 完成 -1 進度條
@property int upload_status; // 執行緒用:0 未處理 1 文字已傳 2 圖片已傳 3 同步成功
@property (nonatomic, strong) NSString *upload_show_text; // 進度百分比文字
@property (nonatomic, getter = isStarting) BOOL starting; // 是否正在進行
@end
DBHelper 用單例封裝 FMDB 操作,並以協定定義介面:
@protocol DBHelperOperation <NSObject>
- (void)onCreate;
- (BOOL)onCreateTable;
- (BOOL)onUpgrade;
- (BOOL)insertOneData:(UploadTable *)table;
- (BOOL)uploadOneData:(UploadTable *)table;
- (BOOL)deleteOneData:(NSString *)table;
- (BOOL)deleteAllData;
- (BOOL)isOneDataExist:(NSString *)upload_id;
- (BOOL)modifyUploadStatus:(NSString *)upload_id andStatus:(int)status;
- (BOOL)modifyUploadProgressStatus:(NSString *)upload_id andStatus:(int)progressStatus;
- (BOOL)modifyStatusAll:(NSString *)upload_id
andStatus:(int)status
andProgressStatus:(int)progressStatus;
- (UploadTable *)queryDataByUploadId:(NSString *)upload_id;
- (NSMutableArray *)queryDataAll;
@end
DBHelper.m 的關鍵片段:
+ (DBHelper *)getInstance {
static DBHelper *instance = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
instance = [[self alloc] init];
[instance onCreate];
[instance onCreateTable];
});
return instance;
}
- (instancetype)init {
self = [super init];
if (self) {
TABLE_NAME = @"table_upload_status";
UPLOAD_ID = @"upload_id";
UPLOAD_NAME = @"upload_name";
UPLOAD_TYPE = @"upload_type";
UPLOAD_TEXT = @"upload_text";
UPLOAD_IMG_NAME = @"upload_img_name";
UPLOAD_IMG_SYS = @"upload_img_sys";
UPLOAD_PROGRESS = @"upload_progress";
UPLOAD_STATUS = @"upload_status";
}
return self;
}
- (void)onCreate {
NSString *docsPath = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *dbPath = [docsPath stringByAppendingPathComponent:@"umpad_upload_manager.db"];
db = [FMDatabase databaseWithPath:dbPath];
}
- (BOOL)onCreateTable {
if (![db open]) return FALSE;
NSString *sql = [NSString stringWithFormat:
@"CREATE TABLE IF NOT EXISTS '%@' ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"'%@' TEXT, '%@' TEXT, '%@' TEXT, '%@' TEXT, '%@' TEXT, '%@' TEXT, "
"'%@' INTEGER, '%@' INTEGER)",
TABLE_NAME, UPLOAD_ID, UPLOAD_NAME, UPLOAD_TYPE, UPLOAD_TEXT,
UPLOAD_IMG_NAME, UPLOAD_IMG_SYS, UPLOAD_PROGRESS, UPLOAD_STATUS];
[db beginTransaction];
BOOL res = [db executeUpdate:sql];
NSLog(@"創建表%@", res ? @"成功" : @"失敗");
[db commit];
[db close];
return res;
}
// 更新線程狀態與 UI 狀態可拆成兩個方法,也可合併為 modifyStatusAll
- (BOOL)modifyStatusAll:(NSString *)upload_id
andStatus:(int)status
andProgressStatus:(int)progressStatus {
if (![db open]) return FALSE;
NSString *sql = [NSString stringWithFormat:
@"UPDATE '%@' SET '%@' = '%d', '%@' = '%d' WHERE '%@' = '%@'",
TABLE_NAME, UPLOAD_PROGRESS, progressStatus,
UPLOAD_STATUS, status, UPLOAD_ID, upload_id];
[db beginTransaction];
BOOL res = [db executeUpdate:sql];
[db commit];
[db close];
return res;
}
- (UploadTable *)queryDataByUploadId:(NSString *)upload_id {
if (![db open]) return nil;
NSString *sql = [NSString stringWithFormat:
@"SELECT * FROM '%@' WHERE '%@' = '%@'", TABLE_NAME, UPLOAD_ID, upload_id];
FMResultSet *rs = [db executeQuery:sql];
UploadTable *result = nil;
if ([rs next]) {
result = [[UploadTable alloc] init];
result.upload_id = [rs stringForColumn:UPLOAD_ID];
result.upload_name = [rs stringForColumn:UPLOAD_NAME];
result.upload_text = [rs stringForColumn:UPLOAD_TEXT];
result.upload_type = [rs stringForColumn:UPLOAD_TYPE];
result.upload_img_name = [rs stringForColumn:UPLOAD_IMG_NAME];
result.upload_img_sys = [rs stringForColumn:UPLOAD_IMG_SYS];
result.upload_progress = [rs intForColumn:UPLOAD_PROGRESS];
result.upload_status = [rs intForColumn:UPLOAD_STATUS];
}
[db close];
return result;
}
@end
ViewController 遵循 MerchantTaskDelegate,在 cellForRowAtIndexPath: 中依狀態顯示文字,並啟動對應任務;任務完成回呼時更新資料來源並刷新該列。
- (void)viewDidLoad {
[super viewDidLoad];
dbHelper = [DBHelper getInstance];
_tableData = [dbHelper queryDataAll]; // 進入頁面即從資料庫恢復未完成的任務
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"uploadTableCell";
UploadTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UploadTableCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier];
}
UploadTable *uploadTable = [_tableData objectAtIndex:indexPath.row];
switch (uploadTable.upload_progress) {
case 0: cell.uploadProgress.text = @"未處理"; break;
case 1: cell.uploadProgress.text = @"文字上傳中"; break;
case 2: cell.uploadProgress.text = @"文字上傳失敗"; break;
case 3: cell.uploadProgress.text = @"圖片未上傳"; break;
case 4: cell.uploadProgress.text = @"圖片上傳中"; break;
case 5: cell.uploadProgress.text = @"圖片上傳失敗"; break;
case 6: cell.uploadProgress.text = @"圖片同步中"; break;
case 7: cell.uploadProgress.text = @"圖片同步失敗"; break;
case 8: cell.uploadProgress.text = @"上傳完成"; break;
case -1: cell.uploadProgress.text = uploadTable.upload_show_text; break;
default: break;
}
cell.dataName.text = uploadTable.upload_name;
cell.dataType.text = uploadTable.upload_type;
cell.upload_id = uploadTable.upload_id;
[self startOperationsForTaskRecord:uploadTable atIndexPath:indexPath];
return cell;
}
#pragma mark - 啟動任務
- (void)startOperationsForTaskRecord:(UploadTable *)record
atIndexPath:(NSIndexPath *)indexPath {
if (!record.isStarting) {
[self startTaskingForRecord:record atIndexPath:indexPath];
}
}
- (void)startTaskingForRecord:(UploadTable *)record
atIndexPath:(NSIndexPath *)indexPath {
// 用 indexPath 作為 key,避免同一列被重複加入佇列
if (![self.pendingOperations.uploadInProgress.allKeys containsObject:indexPath]) {
MerchantTask *task = [[MerchantTask alloc] initWithTaskRecord:record
atIndexPath:indexPath
delegate:self];
[self.pendingOperations.uploadInProgress setObject:task forKey:indexPath];
[self.pendingOperations.uploadQueue addOperation:task];
}
}
#pragma mark - 佇列控制
- (void)suspendAllOperations { [self.pendingOperations.uploadQueue setSuspended:YES]; }
- (void)resumeAllOperations { [self.pendingOperations.uploadQueue setSuspended:NO]; }
- (void)cancelAllOperations { [self.pendingOperations.uploadQueue cancelAllOperations]; }
#pragma mark - 任務完成回呼
- (void)merchantTaskDidFinish:(MerchantTask *)uploader {
NSIndexPath *indexPath = uploader.indexPathInTableView;
UploadTable *theRecord = uploader.taskRecord;
// 1. 把更新後的記錄寫回資料來源
[_tableData replaceObjectAtIndex:indexPath.row withObject:theRecord];
// 2. 持久化,確保 App 被終止後仍能恢復
[dbHelper modifyStatusAll:theRecord.upload_id
andStatus:theRecord.upload_status
andProgressStatus:theRecord.upload_progress];
// 3. 刷新該列
[self.tableView reloadRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationFade];
// 4. 完成後移出進行中字典
if (uploader.taskRecord.upload_status == 3) {
[self.pendingOperations.uploadInProgress removeObjectForKey:indexPath];
[self.pendingOperations.uploadFinishProgress setObject:uploader forKey:indexPath];
}
}
原始實作可以跑,但有幾處在正式專案中必須改善:
SQL 使用字串拼接,有 SQL Injection 風險。所有 stringWithFormat: 拼出來的 SQL 都應改用 executeUpdate:withArgumentsInArray: 的參數化寫法。這不只是安全問題,也能避免資料中含單引號時語法直接出錯。
每次操作都 open / close 資料庫。FMDatabase 非執行緒安全,開關的開銷也不小。建議改用 FMDatabaseQueue,它會序列化所有存取,既安全又免去自己管理鎖。
delegate 宣告為 assign 在 ARC 下有風險。應改為 weak,避免 delegate 被釋放後成為懸空指標。
回呼中直接 reloadRows 而未確認 indexPath 仍有效。若使用者在任務執行中刪除列,會因索引越界而崩潰。實務上應先驗證 indexPath.row < _tableData.count,或改用 reloadData 作為兜底。
任務取消後未清理狀態。cancelAllOperations 只是設旗標,正在執行的 main 仍會跑完。需在長時間迴圈中檢查 [self isCancelled],並在 cancelAllOperations 時同步清空 uploadInProgress 字典。