您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 基礎知識 >> iOS 基礎知識

iOS 基礎:自製 MyData 工具類,把資料庫、網路、快取與加密收攏一處

編輯:iOS 基礎知識

每個 iOS 專案遲早都要面對同一批基礎設施:判斷網路狀態、辨識系統版本、快取圖片、發 GET/POST 請求、加解密、解析 JSON/XML、以及操作 SQLite。與其在每個 controller 裡各寫一遍,不如收攏成一個 MyData 工具類。

以下以我自己專案中的實作為例,程式碼為主、註解為輔,讓大家做工程時多一個選擇。這其實就是自己封裝一層 SQLite 常見 operations,不多說,看程式碼。

一、MyData.h:把 SQL 語句集中成巨集

把 SQL 集中管理是這個設計的第一個重點——所有語句寫在一處,日後改欄位不必全專案搜尋。

/*
 MyData 幾乎每個工程都用得到的 Demo,包含:
 1. iPhone 網路判斷
 2. 系統版本判斷(是否大於 iOS 7)
 3. 圖片快取處理
 4. GET / POST 下載與上傳請求
 5. 加密手段(md5)
 6. 資料解析(JSON / XML)
*/

// ============ 建立資料表 ============
#define MAPPINGDATA  @"create table if not exists mapping(name text,title text)"
#define SHAREDATA    @"create table if not exists sharedata(name text,title text)"
#define JOBDATA      @"create table if not exists job(name text,title text,integral text,taskId text)"
#define BRUSH        @"create table if not exists brush(name text,taskid text,jifen text,url text)"
#define LEAFLETSDATA @"create table if not exists leaft(name text,taskid text,jifen text,url text)"

// ============ 寫入資料 ============
#define TJSJMAPPINGDATA @"insert into mapping(name,title) values(?,?)"
#define TJSJSHAREDATA   @"insert into sharedata(name,title) values(?,?)"
#define TJSJJOBDATA     @"insert into job(name,title,integral,taskId) values(?,?,?,?)"
#define TJSJBRUSH       @"insert into brush(name,taskid,jifen,url) values(?,?,?,?)"

// ============ 讀取資料 ============
#define DQSJMAPPINGDATA @"select * from mapping"
#define DQSJSHAREDATA   @"select * from sharedata"
#define DQSJJOBDATA     @"select * from job"
#define DQSJBRUSH       @"select * from brush"
#define DQLEAFLETSDATA  @"select * from leaft"

// ============ 清空資料表 ============
#define SCSJMAPPINGDATA @"delete from mapping"
#define SCSJSHAREDATA   @"delete from sharedata"
#define SCSJJOBDATA     @"delete from job"
#define SCSJBRUSH       @"delete from brush"
#define SCSJLEAFLETSDATA @"delete from leaft"

二、委派協定:讓網路結果回得來

因為 GET/POST 是非同步的,結果得靠 delegate 回推。這裡設計了四個 overload,分別對應「要不要攜帶進度」、「要不要攜帶 indexPath」,讓呼叫端依場景挑一個實作即可:

#import <Foundation/Foundation.h>
#import <sqlite3.h>

@protocol MyDataDelegate <NSObject>

/*
 參數:
 datas    -> 回傳的資料
 ressNum  -> 下載進度,0 ~ 1
 str      -> 請求的網址
 indexPath -> 對應的列表位置(用於 cell 逐一載入)
 error    -> 是否發生錯誤
*/

@optional
-(void)sendData:(NSMutableData *)datas andProgress:(float)ressNum
        andFilg:(NSString *)str andIndexPath:(NSIndexPath *)indexPath
        andError:(BOOL)error;

-(void)sendData:(NSMutableData *)datas andProgress:(float)ressNum
        andFilg:(NSString *)str andError:(BOOL)error;

-(void)sendData:(NSMutableData *)datas andFilg:(NSString *)str
    andIndexPath:(NSIndexPath *)indexPath andError:(BOOL)error;

-(void)sendData:(NSMutableData *)datas andFilg:(NSString *)str
        andError:(BOOL)error;

@end


@interface MyData : NSObject <NSURLConnectionDataDelegate>

// ============ 實例變數 ============
{
    NSMutableData *receiveData;   // 累積收到的資料
    NSString *urlstr;             // 目前請求的網址
    NSTimer *timer;               // 逾時計時器
    NSURLConnection *connection;  // 用於取消下載
    long long AllLength;          // 檔案總長,用來算進度
}

@property (nonatomic, assign) id<MyDataDelegate> delegate;
@property (nonatomic, assign) NSIndexPath *indexPath;

// ============ 版本判斷 ============
+(BOOL)isIos7;
+(BOOL)isIos6;

// ============ 圖片快取 ============
+(NSString *)picturePath;
+(BOOL)addpicture:(UIImage *)image andAddress:(NSString *)path;
+(BOOL)judgeIsImage:(NSString *)path;
+(UIImage *)obtainImage:(NSString *)path;
+(BOOL)RemoveArrPictures;
+(float)folderSizeAtPath;

// ============ 加密 ============
+(NSString *)md5:(NSString *)str;

// ============ 網路 ============
-(void)downloadGET:(NSString *)urlStr;
-(void)stopDownload;
-(void)postUrl:(NSString *)url andString:(NSString *)string;
+(BOOL)determineNetworkStatus;

// ============ 解析 ============
+(void)jsonFor:(NSMutableArray *)array toIn:(NSData *)data;
+(void)xmlFor:(NSMutableArray *)array toIn:(NSData *)data;

// ============ 上傳圖片 ============
+(NSString *)postRequestWithURL:(NSString *)url
                     postParems:(NSMutableDictionary *)postParems
                      postImage:(UIImage *)image
                       fileName:(NSString *)name;

// ============ 資料庫 ============
+(NSString *)filePath;
@end

三、MyData.m 實作

1. 版本判斷(用 dispatch_once 做單例快取)

static NSUInteger DeviceSystemMajorVersion() {
    static NSUInteger _deviceSystemMajorVersion = -1;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        _deviceSystemMajorVersion = [[[[[UIDevice currentDevice] systemVersion]
            componentsSeparatedByString:@"."] objectAtIndex:0] intValue];
    });
    return _deviceSystemMajorVersion;
}

+(BOOL)isIos7 { return DeviceSystemMajorVersion() >= 7; }
+(BOOL)isIos6 { return DeviceSystemMajorVersion() >= 6; }

用 dispatch_once 快取版本號是個好習慣:不必每次判斷都去解析系統字串。不過實務上更推薦直接比對 NSFoundationVersionNumber 或用 @available(iOS 7.0, *) 讓編譯器幫你檢查可用性。

2. 圖片快取

+(NSString *)picturePath {
    // 存在 Caches 目錄下
    NSString *path = [NSSearchPathForDirectoriesInDomains(
        NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    path = [path stringByAppendingPathComponent:@"圖片緩存"];

    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:path]) {
        [fm createDirectoryAtPath:path withIntermediateDirectories:YES
                        attributes:nil error:nil];
    }
    return path;
}

+(NSString *)picturesName:(NSString *)path {
    // 從 URL 中取出檔名,若沒有已知圖片副檔名則補上 .png
    NSMutableString *str = [NSMutableString stringWithString:path];
    for (int i = path.length - 1; i >= 0; i--) {
        if ([str characterAtIndex:i] == '/') {
            [str deleteCharactersInRange:NSMakeRange(i, 1)];
        }
    }
    return str;
}

+(BOOL)addpicture:(UIImage *)image andAddress:(NSString *)path {
    NSFileManager *file = [NSFileManager defaultManager];
    NSString *pp = [MyData picturePath];
    NSString *lujing = [pp stringByAppendingPathComponent:[MyData picturesName:path]];
    NSData *data = UIImagePNGRepresentation(image);
    return [file createFileAtPath:lujing contents:data attributes:nil];
}

+(BOOL)judgeIsImage:(NSString *)path {
    NSString *string = [[MyData picturePath]
        stringByAppendingPathComponent:[MyData picturesName:path]];
    return [[NSFileManager defaultManager] fileExistsAtPath:string];
}

+(UIImage *)obtainImage:(NSString *)path {
    NSString *lujing = [[MyData picturePath]
        stringByAppendingPathComponent:[MyData picturesName:path]];
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:lujing];
    return [UIImage imageWithData:data];
}

+(BOOL)RemoveArrPictures {
    NSError *error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:[MyData picturePath] error:&error];
    return YES;
}

+(float)folderSizeAtPath {
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *root = [MyData picturePath];

    if (![manager fileExistsAtPath:root]) { return 0; }

    NSEnumerator *childFilesEnumerator =
        [[manager subpathsAtPath:root] objectEnumerator];
    NSString *fileName;
    long long folderSize = 0;

    while ((fileName = [childFilesEnumerator nextObject]) != nil) {
        NSString *fileAbsolutePath = [root stringByAppendingPathComponent:fileName];
        folderSize += [MyData fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize / (1024.0 * 1024.0);   // 回傳 MB
}

把快取放在 Caches 而非 Documents,是因為系統在空間不足時有權回收 Caches 內容;而 Documents 會被 iCloud 備份,塞大量圖片進去會讓使用者備份爆掉。

3. MD5 加密

+(NSString *)md5:(NSString *)str {
    const char *cStr = [str UTF8String];
    unsigned char result[32];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);

    return [NSString stringWithFormat:
        @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
        result[0], result[1], result[2], result[3],
        result[4], result[5], result[6], result[7],
        result[8], result[9], result[10], result[11],
        result[12], result[13], result[14], result[15]];
}

需引入 #import <CommonCrypto/CommonDigest.h>。但要提醒:MD5 已被判定為密碼學上不安全,不應再用於儲存密碼或簽章驗證。它還能用的场合只剩「把長字串壓成短識別碼」或「偵測非惡意性的內容改動」。若要雜湊密碼,請用 bcrypt/scrypt/Argon2;若要完整性驗證,改用 SHA-256 以上。

4. GET 下載與進度回報

-(void)downloadGET:(NSString *)urlStr {
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    connection = [NSURLConnection connectionWithRequest:request delegate:self];
}

-(void)stopDownload {
    [connection cancel];
}

-(void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response {
    receiveData = [[NSMutableData alloc] initWithCapacity:0];
    AllLength = [response expectedContentLength];
    urlstr = [[response URL] absoluteString];
}

-(void)connection:(NSURLConnection *)connection
    didReceiveData:(NSData *)data {
    [receiveData appendData:data];

    float proportion = (float)[receiveData length] / (float)AllLength;

    if ([self.delegate respondsToSelector:@selector(sendData:andProgress:andFilg:andIndexPath:andError:)]) {
        [self.delegate sendData:receiveData andProgress:proportion
                        andFilg:urlstr andIndexPath:self.indexPath andError:NO];
    }
    if ([self.delegate respondsToSelector:@selector(sendData:andProgress:andFilg:andError:)]) {
        [self.delegate sendData:receiveData andProgress:proportion
                        andFilg:urlstr andError:NO];
    }
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if ([self.delegate respondsToSelector:@selector(sendData:andProgress:andFilg:andIndexPath:andError:)]) {
        [self.delegate sendData:receiveData andProgress:1
                        andFilg:urlstr andIndexPath:nil andError:NO];
    }
    // 其餘 overload 同理
}

-(void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error {
    // 各 overload 都以「訪問超時」與 error:YES 回報
}

進度計算的關鍵就是 expectedContentLength 搭配已接收位元組數。注意 expectedContentLength 在未知大小時會回傳 NSURLResponseUnknownLength(-1),此時要記得避開除法,否則進度會變成負數。

5. POST 請求

-(void)postUrl:(NSString *)url andString:(NSString *)string {
    NSMutableData *postData = [[NSMutableData alloc] init];
    [postData appendData:[string dataUsingEncoding:NSUTF8StringEncoding]];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
        cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];

    connection = [NSURLConnection connectionWithRequest:request delegate:self];
}

6. 網路狀態判斷

+(BOOL)determineNetworkStatus {
    Reachability *r = [Reachability reachabilityForInternetConnection];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:      return NO;
        case ReachableViaWiFi:  return YES;
        case ReachableViaWWAN:  return YES;
        default:                return NO;
    }
}

7. JSON 與 XML 解析

+(void)jsonFor:(NSMutableArray *)array toIn:(NSData *)data {
    [array removeAllObjects];

    // 方法一:系統原生 API
    NSArray *arr = [NSJSONSerialization JSONObjectWithData:data
                                                  options:NSJSONReadingAllowFragments
                                                    error:nil];
    [array setArray:arr];

    // 方法二:第三方(JSON.h)
    // NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    // [array setArray:[str JSONValue]];
}

+(void)xmlFor:(NSMutableArray *)array toIn:(NSData *)data {
    [array removeAllObjects];

    NSError *error = nil;
    GDataXMLDocument *document =
        [[GDataXMLDocument alloc] initWithData:data options:0 error:&error];
    GDataXMLElement *element = [document rootElement];

    for (GDataXMLElement *e in [element elementsForName:@"student"]) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setObject:[[e elementsForName:@"name"] lastObject].stringValue forKey:@"name"];
        [dic setObject:[[e elementsForName:@"age"]  lastObject].stringValue forKey:@"age"];
        [dic setObject:[[e elementsForName:@"sex"]  lastObject].stringValue forKey:@"sex"];
        [array addObject:dic];
    }
}

8. 上傳圖片(multipart/form-data)

上傳檔案的核心是手工組出 multipart 本文:先用 boundary 分隔各個欄位,最後再把二進位圖片資料接上去。

+(NSString *)postRequestWithURL:(NSString *)url
                     postParems:(NSMutableDictionary *)postParems
                      postImage:(UIImage *)image
                       fileName:(NSString *)name {

    NSString *BOUNDARY = @"0xKhTmLbOuNdArY";

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
        cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];

    NSData *data = nil;
    if (image) {
        data = UIImageJPEGRepresentation(image, 0.1);
    }

    NSMutableString *body = [[NSMutableString alloc] init];
    NSString *MPboundary = [NSString stringWithFormat:@"--%@", BOUNDARY];
    NSString *endMPboundary = [NSString stringWithFormat:@"%@--", MPboundary];

    // 先放一般欄位
    for (NSString *key in [postParems allKeys]) {
        [body appendFormat:@"%@\r\n", MPboundary];
        [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key];
        [body appendFormat:@"%@\r\n", [postParems objectForKey:key]];
    }

    // 再放檔案欄位
    if (image) {
        [body appendFormat:@"%@\r\n", MPboundary];
        [body appendFormat:@"Content-Disposition: form-data; name=\"uploadFile\"; filename=\"%@\"\r\n", name];
        [body appendFormat:@"Content-Type: image/jpg\r\n\r\n"];
    }

    NSString *end = [NSString stringWithFormat:@"\r\n%@", endMPboundary];

    NSMutableData *myRequestData = [NSMutableData data];
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    if (image) { [myRequestData appendData:data]; }
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];

    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", BOUNDARY]
   forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]]
   forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:myRequestData];
    [request setHTTPMethod:@"POST"];

    NSHTTPURLResponse *urlResponse = nil;
    NSError *error = nil;
    NSData *resultData = [NSURLConnection sendSynchronousRequest:request
                                              returningResponse:&urlResponse
                                                          error:&error];

    if (urlResponse.statusCode >= 200 && urlResponse.statusCode < 300) {
        return [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
    }
    return nil;
}

9. SQLite 操作

資料庫放在 Caches 下的 shuJu.sqlite,並把「開表 → 準備 statement → 綁定參數 → 執行 → 收尾」五步固定下來:

+(NSString *)filePath {
    NSString *path = [NSSearchPathForDirectoriesInDomains(
        NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    return [path stringByAppendingPathComponent:@"shuJu.sqlite"];
}

// 建立表單
+(BOOL)chuangJianTable:(NSString *)string {
    sqlite3_open([[MyData filePath] UTF8String], &db);
    if (!db) { NSLog(@"數據庫打開失敗!"); return NO; }

    sqlite3_stmt *stmt = nil;
    if (sqlite3_prepare_v2(db, [string UTF8String], -1, &stmt, nil) == SQLITE_OK) {
        if (sqlite3_step(stmt) == SQLITE_DONE) { NSLog(@"創建成功!"); }
    }

    sqlite3_finalize(stmt);
    sqlite3_close(db);
    return YES;
}

// 寫入
+(BOOL)cunMappingDataOfName:(NSString *)name andString:(NSString *)title {
    [MyData chuangJianTable:MAPPINGDATA];

    sqlite3_open([[MyData filePath] UTF8String], &db);
    if (!db) { NSLog(@"數據庫打開失敗!"); return NO; }

    sqlite3_stmt *stmt = nil;
    if (sqlite3_prepare(db, [TJSJMAPPINGDATA UTF8String], -1, &stmt, nil) == SQLITE_OK) {
        // 問號編號從 1 開始
        sqlite3_bind_text(stmt, 1, name.length > 0 ? [name UTF8String] : [@"100" UTF8String], -1, nil);
        sqlite3_bind_text(stmt, 2, title.length > 0 ? [title UTF8String] : [@"預設值" UTF8String], -1, nil);
    }

    if (sqlite3_step(stmt) == SQLITE_DONE) { NSLog(@"添加成功!"); }

    sqlite3_finalize(stmt);
    sqlite3_close(db);
    return YES;
}

// 讀取
+(NSMutableArray *)quMappingData {
    NSMutableArray *arr = [[NSMutableArray alloc] init];

    sqlite3_open([[MyData filePath] UTF8String], &db);
    if (db == nil) { NSLog(@"數據庫打開失敗"); return arr; }

    sqlite3_stmt *stmt = nil;
    if (sqlite3_prepare_v2(db, [DQSJMAPPINGDATA UTF8String], -1, &stmt, nil) == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            char *name  = (char *)sqlite3_column_text(stmt, 0);
            char *title = (char *)sqlite3_column_text(stmt, 1);

            NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
            [dic setObject:[NSString stringWithCString:name encoding:NSUTF8StringEncoding]
                    forKey:@"name"];
            [dic setObject:[NSString stringWithCString:title encoding:NSUTF8StringEncoding]
                    forKey:@"title"];
            [arr addObject:dic];
        }
    }

    sqlite3_finalize(stmt);
    sqlite3_close(db);
    return arr;
}

// 刪除全部
+(BOOL)shanMappingData {
    sqlite3_open([[MyData filePath] UTF8String], &db);
    if (!db) { return NO; }

    sqlite3_stmt *stmt = nil;
    if (sqlite3_prepare_v2(db, [SCSJMAPPINGDATA UTF8String], -1, &stmt, nil) == SQLITE_OK) {
        if (sqlite3_step(stmt) == SQLITE_DONE) { NSLog(@"刪除成功!"); }
    }

    sqlite3_finalize(stmt);
    sqlite3_close(db);
    return YES;
}

這份設計值得借鏡的地方

  • SQL 集中成巨集,改 schema 時只需動一處。
  • delegate 的多個 overload,讓不同 caller 只實作自己需要的簽名,不必被不需要的參數綁住。
  • 快取放 Caches 而非 Documents,避免圖片被 iCloud 備份。
  • 進度回報靠 expectedContentLength,這是所有下載進度條的共同基礎。

但正式專案請不要這樣寫

這個 MyData 作為學習與理解原理的教材很好,但直接搬進 production 專案會遇到幾個問題,誠實列出來比粉飾太平有用:

  • NSURLConnection 已於 iOS 9 被標記為廢棄,且 sendSynchronousRequest: 會封鎖主執行緒造成畫面凍結。請改用 NSURLSession,並用 dataTask 的 completion handler 或 delegate 模式。
  • static 單例 sqlite3 handle 不是執行緒安全的。多執行緒共用同一個 db 指標會出現難以重現的崩潰。每個連線應該各自持有 handle,或改用 FMDB 的 FMDatabaseQueue 把存取序列化。
  • 每次操作都 open / close 資料庫,成本很高。實務上應保持連線長開,只在合適時機(如進入背景)才關閉。
  • 沒有使用 prepare 的錯誤處理,也沒有 sqlite3_finalize 之外的資源保護。任何一步失敗都應 early return 並記錄錯誤。
  • 把密碼相關的雜湊交給 MD5 是不安全的,如前所述請改用 bcrypt 系列或 SHA-256 以上,並在伺服器端加鹽。
  • 「判斷是否 iOS 7」這類版本判斷已無意義,請改用 @available 或 if (@available(iOS 11, *)) 讓編譯器幫你檢查。
  • delegate 用 assign 而非 weak 有懸空指標風險,ARC 專案請一律改用 weak。

結論:把 MyData 當成「這些基礎設施長什麼樣子」的參照,理解每一塊的原理,然後在真實專案裡改用 NSURLSession + Codable + FMDB/Core Data + Keychain 這套現代組合。原理是通用的,API 會過時——知道自己在做什麼,換 API 只是查文件的問題。

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