您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 多線程、ASI、AFN 與 UIWebView 綜合筆記

編輯:iOS 開發綜合

這篇把四個常被一起問到的主題整理在一塊:多線程的四種寫法、兩個主流網路庫的斷點續傳,以及 UIWebView 的載入方式。

一、多線程售票:同一個問題的四種解法

用「一百張票、多個窗口同時賣」這個經典題目,可以清楚比較 NSThread、NSOperationQueue 與 GCD 的差異。核心難題只有一個:共享資源。

@interface ViewController () {
    NSInteger _tickets;
    NSLock *_lock;          // 線程鎖必須是成員變量,不能是局部變量
}
@property (assign, atomic) NSInteger tickets;
@end

這裡的設計準則有兩條:搶奪的資源必須是 atomic 屬性;讀寫時一律透過 self.xxx 呼叫 getter,這樣 atomic 才會真正發揮作用。

NSThread 版:需要自己加鎖

- (IBAction)threadSales:(id)sender {
    _tickets = 100;

    NSThread *thread1 = [[NSThread alloc] initWithTarget:self
                                               selector:@selector(threadSaleMethod)
                                                 object:nil];
    [thread1 setName:@"售票線程-1"];
    [thread1 start];   // 只有 NSThread 需要手動 start

    NSThread *thread2 = [[NSThread alloc] initWithTarget:self
                                               selector:@selector(threadSaleMethod)
                                                 object:nil];
    [thread2 setName:@"售票線程-2"];
    [thread2 start];
}

- (void)threadSaleMethod {
    if (_lock == nil) {
        _lock = [[NSLock alloc] init];   // 懶加載
    }

    while (YES) {
        [_lock lock];                    // 使用共享資源前先上鎖
        if (_tickets > 0) {
            NSString *str = [NSString stringWithFormat:@"當前票數是%d,售票線程是%@",
                             _tickets, [[NSThread currentThread] name]];
            [self performSelectorOnMainThread:@selector(appendTextView:)
                                  withObject:str waitUntilDone:YES];
            _tickets--;
            [_lock unlock];              // 用完立刻解鎖

            // 模擬不同售票效率
            [[[NSThread currentThread] name] isEqualToString:@"售票線程-1"]
                ? [NSThread sleepForTimeInterval:0.2]
                : [NSThread sleepForTimeInterval:0.3];
        } else {
            [_lock unlock];
            [self performSelectorOnMainThread:@selector(appendTextView:)
                                  withObject:@"票已售完" waitUntilDone:YES];
            break;
        }
    }
}

值得學會的習慣是:在子線程中不要直接更新 UI,必須透過 performSelectorOnMainThread 切回主線程。另外注意加鎖的範圍要盡量小,只在讀寫共享資源時上鎖,模擬延時則放在鎖外,否則會把並行優勢抵銷掉。

NSOperation 版:改用同步鎖區塊

- (IBAction)invocationSales:(id)sender {
    _tickets = 20;

    NSInvocationOperation *op1 = [[NSInvocationOperation alloc]
        initWithTarget:self selector:@selector(operationSaleMethod:) object:@"Operation - 1"];
    NSInvocationOperation *op2 = [[NSInvocationOperation alloc]
        initWithTarget:self selector:@selector(operationSaleMethod:) object:@"Operation - 2"];

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:op1];   // 加入佇列即自動啟動
    [queue addOperation:op2];
}

- (void)operationSaleMethod:(NSString *)operationName {
    while (YES) {
        @synchronized (self) {       // 同步區塊取代手動 lock / unlock
            if (self.tickets > 0) {
                NSString *str = [NSString stringWithFormat:@"當前票數:%d,線程:%@",
                                 self.tickets, operationName];
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    [self appendTextView:str];   // 主佇列只負責更新 UI
                }];
                self.tickets--;
            } else {
                break;
            }
        }
    }
}

// block 版本寫法
- (IBAction)blockSales:(id)sender {
    _tickets = 20;
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperationWithBlock:^{ [self operationSaleMethod:@"Block - 1"]; }];
    [queue addOperationWithBlock:^{ [self operationSaleMethod:@"Block - 2"]; }];
    [queue setMaxConcurrentOperationCount:2];   // 限制最大併發數
}

@synchronized 的好處是不必操心 unlock 的時機,即使中途 return 或拋出例外也會自動釋放;代價是效能略低於 NSLock。setMaxConcurrentOperationCount 則是控制併發的關鍵,設為 1 就等同序列執行。

GCD 版:最簡潔

- (IBAction)gcdSales:(id)sender {
    _tickets = 20;

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();

    dispatch_group_async(group, queue, ^{ [self gcdSaleMethod:@"GCD-1"]; });
    dispatch_group_async(group, queue, ^{ [self gcdSaleMethod:@"GCD-2"]; });

    // 所有任務完成後回到主線程收尾
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self appendTextView:@"票已售完!"];
    });
}

- (void)gcdSaleMethod:(NSString *)gcdName {
    while (YES) {
        if (_tickets > 0) {
            NSString *str = [NSString stringWithFormat:@"當前票數:%d,線程:%@",
                             _tickets, gcdName];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self appendTextView:str];
                _tickets--;      // 對共用資源的修改也放回主佇列
            });
        } else {
            break;
        }
    }
}

dispatch_group_notify 是 GCD 裡最實用的一招:把多個非同步任務「等齊之後再做某事」這件事,用一行表達完畢,不必自己維護計數器。

二、ASI:不支援 ARC 的老牌庫

ASIHTTPRequest 的整合步驟頗繁瑣,值得記錄:

建立專案時不能勾選 ARC;把 Classes 與 External 兩個目錄拖進工程;編譯會報找不到 libxml/HTMLparser.h,解法是在 Build Settings 的 Header Search Paths 加入 ${SDK_DIR}/usr/include/libxml2;接著會抱怨缺少 GHUnit 框架,那是單元測試的相依,進 Build Phases 的 Compile Sources 把檔名以 tests 結尾者全部移除;最後再補上 CFNetwork、SystemConfiguration、MobileCoreServices、libz.dylib、libxml2.dylib 這五個框架即可。

- (IBAction)downloadFile:(id)sender {
    NSString *urlString = @"https://teacher.local/~apple/itcast/download/book.zip";
    NSURL *url = [NSURL URLWithString:urlString];

    NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                             NSUserDomainMask, YES);
    NSString *downloadPath = [documents[0] stringByAppendingPathComponent:@"book.zip"];
    NSString *tempPath     = [documents[0] stringByAppendingPathComponent:@"book.tmp"];

    ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
    [request setDelegate:self];
    [request setDownloadDestinationPath:downloadPath];
    [request setTemporaryFileDownloadPath:tempPath];
    [request setAllowResumeForFileDownloads:YES];   // 斷點續傳
    [request setDownloadProgressDelegate:self];
    [request start];
}

// 取得檔案長度,換算成 MB 更貼近使用者認知
- (void)request:(ASIHTTPRequest *)request
didReceiveResponseHeaders:(NSDictionary *)responseHeaders {
    NSInteger length = [responseHeaders[@"Content-Length"] integerValue];
    _fileLength = (CGFloat)length / 1024 / 1024;
}

- (void)setProgress:(float)newProgress {
    NSLog(@"還差 %.2f MB", newProgress * _fileLength);
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                             NSUserDomainMask, YES);
    NSString *downloadPath = [documents[0] stringByAppendingPathComponent:@"book.zip"];
    [SSZipArchive unzipFileAtPath:downloadPath toDestination:documents[0]];
    [[NSFileManager defaultManager] removeItemAtPath:downloadPath error:nil];
}

三、AFN:ARC 友善、設定更省事

AFNetworking 的整合相對輕鬆:新建專案時可以勾選 ARC;拖入 AFNetworking 與 SSZipArchive,並補上 libz.dylib;編譯若出現警告,補 SystemConfiguration.framework 與 MobileCoreServices.framework;最後在 專案名-Prefix.pch 的 #endif 之前加上兩個 import 即可。

- (IBAction)downloadFiles:(id)sender {
    NSURL *url = [NSURL URLWithString:@"https://169.254.98.245/~apple/itcast/download/book.zip"];
    NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                             NSUserDomainMask, YES);
    NSString *downloadPath = [documents[0] stringByAppendingPathComponent:@"book.zip"];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPRequestOperation *operation =
        [[AFHTTPRequestOperation alloc] initWithRequest:request];

    // 網路資料以串流方式傳輸,用輸出流直接落地
    [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:downloadPath append:NO]];

    [operation setDownloadProgressBlock:^(NSUInteger bytesRead,
                                          long long totalBytesRead,
                                          long long totalBytesExpectedToRead) {
        NSLog(@"下載百分比:%f", (float)totalBytesRead / totalBytesExpectedToRead);
    }];

    [operation setCompletionBlock:^{
        [SSZipArchive unzipFileAtPath:downloadPath toDestination:documents[0]];
        [[NSFileManager defaultManager] removeItemAtPath:downloadPath error:nil];
    }];

    [operation start];
}

四、UIWebView:載入本地內容的三種途徑

// 以 PDF 為例:先由絕對路徑取得 fileURL,再建請求
- (void)viewLocalPDFFile {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"guide.pdf" ofType:nil];
    NSURL *fileURL = [NSURL fileURLWithPath:path];

    NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];
    [_localWebView setDataDetectorTypes:UIDataDetectorTypeAll];
    [_localWebView loadRequest:request];
}

// 以 NSData 載入:MIMEType 必須自己指定
- (void)loadData {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"guide.pdf" ofType:nil];
    NSData *data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:path]];
    [_localWebView loadData:data
                   MIMEType:@"application/pdf"
           textEncodingName:@"UTF-8"
                    baseURL:nil];
}

// 載入 HTML 片段
- (void)loadHTMLString {
    NSString *partHtml = @"<h1>我愛你!!!</h1>";
    [_localWebView loadHTMLString:partHtml baseURL:nil];
}

做一個簡單瀏覽器時,還需要實作 UIWebViewDelegate 的四個方法(shouldStartLoad、didStartLoad、didFinishLoad、didFailLoadWithError),並用 goBack、goForward、reload 對應工具列上的四顆按鈕。

// 網頁中的每個請求都會經過這裡,回傳 NO 可攔下(常用於 JS 與原生互動)
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType {
    return YES;
}

// 用 JS 取得頁面資訊或提交表單
- (IBAction)submit:(id)sender {
    NSString *url   = [_webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
    NSString *title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    [_webView stringByEvaluatingJavaScriptFromString:@"document.forms[0].submit();"];
}

載入本地 HTML 時別忘了指定 baseURL,否則頁面中引用的 CSS、JS 與圖片會全部載不到:

NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]
                             isDirectory:YES];

五、幾個總結性的提醒

多線程部分,三種技術的共同原則是:共享資源必須保護、UI 更新必須回到主線程、鎖的範圍越小越好。GCD 的寫法最簡潔,NSOperation 的優勢在於可取消與可設定相依關係。

網路庫部分,ASI 早已停止維護且不支援 ARC,新專案請勿採用。AFNetworking 的 AFHTTPRequestOperation 也已由 AFURLSessionManager 取代,而兩者如今都應讓位給系統原生的 NSURLSession——它天生支援斷點續傳、背景下載與進度回報。

UIWebView 部分,自 iOS 12 起已被標記為 deprecated,且 Apple 已不再接受僅使用 UIWebView 的新上架或更新。請改用 WKWebView,並以 WKNavigationDelegate 取代原有的 delegate,以 WKUserContentController 取代 stringByEvaluatingJavaScriptFromString 做雙向溝通。

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