標籤:des style blog color io os ar for sp
1 一、NSURLConnection 2 1.發送請求 3 1> 發送一個同步請求 4 + (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error; 5 6 2> 發送一個非同步請求(block) 7 + (void)sendAsynchronousRequest:(NSURLRequest*) request 8 queue:(NSOperationQueue*) queue 9 completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler;10 11 3> 發送一個非同步請求(代理方法)12 [NSURLConnection connectionWithRequest:request delegate:self];13 [[NSURLConnection alloc] initWithRequest:request delegate:self];14 [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];15 16 NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];17 [conn start];18 19 2.檔案下載(大檔案下載)20 1> 實現方案 : 邊下載邊寫入(寫到沙箱的某個檔案中)21 2> 具體實現步驟22 a. 在接收到伺服器的響應時23 // 建立一個空檔案 - NSFileManager24 [mgr createFileAtPath:self.destPath contents:nil attributes:nil];25 26 // 建立一個跟空檔案相關聯的控制代碼對象 - NSFileHandle27 [NSFileHandle fileHandleForWritingAtPath:self.destPath];28 29 b. 在接收到伺服器的資料時30 // 利用控制代碼對象將伺服器返回的資料寫到檔案的末尾31 // 移動到檔案的尾部32 [self.writeHandle seekToEndOfFile];33 // 從當前移動的位置(檔案尾部)開始寫入資料34 [self.writeHandle writeData:data];35 36 c. 在接收完伺服器返回的資料時37 // 關閉控制代碼38 [self.writeHandle closeFile];39 self.writeHandle = nil;40 41 3.斷點下載42 1> 關鍵技術點43 * 佈建要求頭Range, 告訴伺服器下載哪一段資料44 45 4.檔案上傳46 1> 明確47 * 只能用POST請求48 * 請求參數都在請求體(檔案參數\非檔案類型的普通參數)49 50 2> 實現步驟51 a. 拼接請求體(檔案參數\非檔案類型的普通參數)52 * 檔案參數53 // 參數的開始標記(分割線)54 --nihao\r\n55 // 參數描述(參數名...)56 Content-Disposition: form-data; name="參數名"; filename="檔案名稱"\r\n57 // 檔案類型58 Content-Type: 檔案的類型MIMEType\r\n59 // 檔案的位元據(參數值)60 \r\n61 檔案的位元據62 \r\n63 64 * 非檔案參數(普通參數)65 // 參數的開始標記(分割線)66 --nihao\r\n67 // 參數描述(參數名...)68 Content-Disposition: form-data; name="參數名"\r\n69 // 參數值70 \r\n71 參數值72 \r\n73 74 * 所有參數結束的標記75 --nihao--\r\n76 77 b. 佈建要求頭78 * 請求體的長度79 Content-Length : 請求體的長度(位元組長度)80 81 * 請求資料的類型82 Content-Type :83 // 普通POST請求: application/x-www-form-urlencoded84 // 上傳檔案的POST請求 : multipart/form-data; boundary=--nihao
iOS之NSURLConnection詳解(2)