多線程
- NSThread
- GCD
- 隊(duì)列
- 任務(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)求
// 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];
// 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)(大文件下載)
// 創(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];
// 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
}
文件上傳
[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ù)據(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
// 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);
}];
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
- ...
加載方式
[self.webView loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"]]];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"泡沫.mp4" ofType:nil]]]];
self.webView loadData:<#(nonnull NSData *)#> MIMEType:<#(nonnull NSString *)#> textEncodingName:<#(nonnull NSString *)#> baseURL:<#(nonnull NSURL *)#>
[self.webView loadHTMLString:@"<html><body><div style=\"color:red; font-size:20px; border:1px solid blue;\">爽爽爽爽爽</div></body><html>" baseURL:nil];