多線程與網(wǎng)絡(luò) - 概況

多線程

  • NSThread
  • GCD
    • 隊(duì)列
      • 并發(fā)隊(duì)列
        • 全局隊(duì)列
        • 自己創(chuàng)建
      • 串行隊(duì)列
        • 主隊(duì)列
        • 自己創(chuàng)建
    • 任務(wù):block
    • 函數(shù)
      • sync:同步函數(shù)
      • async:異步函數(shù)
    • 單例模式
  • NSOperation & NSOperationQueue
  • RunLoop
    • 同一時(shí)間只能選擇一個(gè)模式運(yùn)行
    • 常用模式
      • Default:默認(rèn)
      • Tacking:拖拽UIScrollView

網(wǎng)絡(luò)

HTTP請(qǐng)求

  • GET請(qǐng)求
// url轉(zhuǎn)碼:
NSString *urlStr = @"http://可能有中文.com";
// stringByAddingPercentEscapesUsingEncoding方法在iOS9中已被棄用
// urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// 改用:
urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
// URL
NSURL *url = [NSURL URLWithString:urlStr];
    
// 請(qǐng)求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
  • POST請(qǐng)求
// url轉(zhuǎn)碼:
NSString *urlStr = @"http://可能有中文.com";
urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

// URL
NSURL *url = [NSURL URLWithString:urlStr];
    
// 請(qǐng)求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"username=123&pwd=456" dataUsingEncoding:NSUTF8StringEncoding];

NSURLConnection(iOS9之后已經(jīng)過期)

NSURLSession

發(fā)送一般的GET/POST請(qǐng)求
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
}];

[task resume];
下載文件 - 不需要離線斷點(diǎn)(小文件下載)
NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
}];
    
[task resume];
下載文件 - 需要離線斷點(diǎn)(大文件下載)
  • 開啟任務(wù)
// 創(chuàng)建session
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration ] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    
// 設(shè)置請(qǐng)求頭(告訴服務(wù)器從哪個(gè)字節(jié)開始下載)
[request setValue:@"bytes=1024-" forHTTPHeaderField:@"Range"];
    
// 創(chuàng)建任務(wù)
NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
    
// 開啟任務(wù)
[task resume];
  • 實(shí)現(xiàn)代理方法
// 1.接收到響應(yīng)
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    // 打開 NSOutputStream
    // 獲得文件的總長度
    // 存儲(chǔ)文件的總長度
    // 回調(diào)返回的 block(允許接收數(shù)據(jù))
    completionHandler(NSURLSessionResponseAllow);
}

// 2.接收到服務(wù)器返回的數(shù)據(jù)(這個(gè)方法可能會(huì)被調(diào)用多次)
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    // 利用NSOutputStream寫入數(shù)據(jù)
    // 計(jì)算下載進(jìn)度
}

// 3.請(qǐng)求完畢
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    // 關(guān)閉并清空NSOutputStream
    // 清空任務(wù)task
}
文件上傳
  • 設(shè)置請(qǐng)求頭
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", JPBoundary] forHTTPHeaderField:@"Content-Type"];
  • 拼接請(qǐng)求體
    • 文件參數(shù)
    • 其他參數(shù)(非文件參數(shù))
  • 開啟任務(wù)
//創(chuàng)建session
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration ] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];

// NSURLSessionUploadTask繼承于NSURLSessionDataTask,所以是遵守NSURLSessionDataDelegate
NSURLSessionUploadTask *task = [self.session uploadTaskWithRequest:request fromData:[self body] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

}];

[task resume];
  • 實(shí)現(xiàn)代理方法
//上傳數(shù)據(jù)
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
    // 計(jì)算上傳進(jìn)度
    NSLog(@"didSendBodyData %lf", 1.0 * totalBytesSent / totalBytesExpectedToSend);
}

// 請(qǐng)求結(jié)束(根據(jù)error判斷是否成功)
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    NSLog(@"didCompleteWithError");
}

AFNetworking

  • GET
// AFHTTPSessionManager:專門管理http請(qǐng)求操作(內(nèi)部包裝了NSURLSession)
AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];

NSDictionary *parame = @{@"username": @"123", @"pwd": @"456"};

[manger GET:BaseURL parameters:parame success:^(NSURLSessionDataTask *task, id responseObject) {
    NSLog(@"%@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"%@", error);
}];
  • POST
AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];

NSDictionary *parame = @{@"username": @"123", @"pwd": @"456"};

[manger POST:BaseURL parameters:parame success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
}];
  • 文件上傳
AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    
[manger POST:@"http://120.25.226.186:32812/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
    NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"minion_15" ofType:@"png"]];
        
    // 在block中設(shè)置需要上傳的文件
    // name:請(qǐng)求參數(shù)名,服務(wù)器給的參數(shù)名稱接口
    // fileName:上傳的文件名
        
    // 方法一(需要自己定義mimeType)
    [formData appendPartWithFileData:data name:@"file" fileName:@"minion_15.png" mimeType:@"image/png"];
        
    // 方法二(根據(jù)文件后綴名獲取mimeType)
    // [formData appendPartWithFileURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"minion_15" ofType:@"png"]] name:@"file" fileName:@"minion_15.png" mimeType:@"image/png" error:nil];
        
    // 方法三(使用上傳文件名當(dāng)作fileName)
    // [formData appendPartWithFileURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"minion_15" ofType:@"png"]] name:@"file" error:nil];
        
} success:^(NSURLSessionDataTask *task, id responseObject) {
    NSLog(@"%@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"%@", error);
}];

// 上傳進(jìn)度
[manger setTaskDidSendBodyDataBlock:^(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
    NSLog(@"DidSendBodyDataBlock %lf", 1.0 * totalBytesSent / totalBytesExpectedToSend);
}];

UIWebView

UIWebView是iOS內(nèi)置的瀏覽器控件,系統(tǒng)自帶Safari瀏覽器就是通過UIWebView實(shí)現(xiàn)的
UIWebView不但能加載遠(yuǎn)程的網(wǎng)頁資源,還能加載絕大部分的常見文件
  • html\htm
  • pdf、doc、ppt、txt
  • mp4
  • ...
加載方式
  • 加載本地html文件
[self.webView loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"]]];
  • 加載網(wǎng)絡(luò)url
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]];
  • 加載本地文件
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"泡沫.mp4" ofType:nil]]]];
  • 加載data
self.webView loadData:<#(nonnull NSData *)#> MIMEType:<#(nonnull NSString *)#> textEncodingName:<#(nonnull NSString *)#> baseURL:<#(nonnull NSURL *)#>
  • 加載html
[self.webView loadHTMLString:@"<html><body><div style=\"color:red; font-size:20px; border:1px solid blue;\">爽爽爽爽爽</div></body><html>" baseURL:nil];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • iOS開發(fā)系列--網(wǎng)絡(luò)開發(fā) 概覽 大部分應(yīng)用程序都或多或少會(huì)牽扯到網(wǎng)絡(luò)開發(fā),例如說新浪微博、微信等,這些應(yīng)用本身可...
    lichengjin閱讀 4,036評(píng)論 2 7
  • IOS之UIWebView的使用 剛接觸IOS開發(fā)1年多,現(xiàn)在對(duì)于 混合式 移動(dòng)端開發(fā)越來越流行,因?yàn)殚_發(fā)成本上、...
    學(xué)無止境666閱讀 46,008評(píng)論 5 53
  • OS之UIWebView的使用 剛接觸IOS開發(fā)1年多,現(xiàn)在對(duì)于 混合式 移動(dòng)端開發(fā)越來越流行,因?yàn)殚_發(fā)成本上、速...
    知之未道閱讀 1,711評(píng)論 0 4
  • 1 概念性知識(shí) 01 webView是有缺點(diǎn)的,會(huì)導(dǎo)致內(nèi)存泄露,而且這個(gè)問題是它系統(tǒng)本身的問題。 02 手機(jī)上面的...
    BEYOND黃閱讀 399評(píng)論 0 0
  • 我以為每個(gè)人都是獨(dú)立以及個(gè)體,都是不同的 后來我發(fā)現(xiàn),那只是你以為 許多...
    AliceDan閱讀 236評(píng)論 0 0

友情鏈接更多精彩內(nèi)容