天天看點

企業級iOS應用開發實戰(看書筆記)

企業應用篇(包含網絡、資料庫、安全等)

一、網絡

1、使用NSURLConnection獲得網絡資料(NSURL和NSURLRequest基于網絡HTTP程式設計)

      (1)最簡單的情況下

       NSURL可以引用網絡或本地資源,是URL的一個包裝,使用URL,需要建立一個NSURL對象,然後從NSURL獲得資料:

NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
           

       NSURLRequest通常結合UIWebView一起使用,首先建立一個NSURL,然後轉換為NSURLRequest,最終在UIWebView中讀取網頁内容:

NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
           

      (2)需要一種更特定的方式處理HTTP資料時(異步請求/POST資料)

      NSURLMutableRequest/NSURLConnection

NSURL* url = [ NSURL URLWithString:@" http:// www. apple. com"];
NSMutableURLRequest* request = [[ NSMutableURLRequest alloc] initWithURL:url cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval: 60];//初始化NSMutableURLRequest,同時指定cache的使用方式和逾時時間
receivedData = [[ NSMutableData alloc] init]; 
[request setHTTPMethod:@" GET"]; 
[request addValue:@" text/ html" forHTTPHeaderField:@" Content- Type"];
NSURLConnection* conn = [[ NSURLConnection alloc] initWithRequest: request delegate:self];