標籤:
1. 兩部分: 連結並擷取資料 從擷取到資料構建資料模型2.通過HTTP協議於web伺服器通訊 `瀏覽器發送一個請求給制定的url地址,url返回求情頁。HTML以及圖片 `瀏覽器發生帶有其他參數的比如是表資料 給制定的伺服器,伺服器返回一個自訂的或者動態活著web page3.資料格式一般是JSON或者XML4.請求的url格式。 一般沒有特定的格式,只要伺服器能識別即可。比如灰騰騰p://bookapi.bignerdranch.com/course.json http://baseURL.com/serviceName?argumentX=valueX&argumentY=valueY 比如擷取指定時間的課程內容: http://bignerdranch.com/course?year=2014&month=11 !!!url地址不能包好空格等一些特殊字元,如果有需要,你要進行轉義 NSString *search = @"Play some \"Abba\""; NSString *escaped = [search stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 解析地址 - (NSString *)stringByRemovingPercentEncoding;5.使用URLSession NSURLSession *session; NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionCofiguration]; session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:nil]; 建立帶一個configuration以及delegate,delegateQueue 預設可以為nil 擷取資料: -(void)fetchFeed { NSString *requestString = @"http://bignerdranch.com/course.json"; NSURL *url = [NSURL URLWithString:requestString]; NSURLRequest *req = [NSURLRequest requestWithURL:url]; NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){ NSString *json = [[NSString alloc] stringWithData: data encoding:NSUTF8StringEncoding]; }]; [dataTask resume]; } 使用session建立dataTask6.JSON資料 解析:使用內建原生類NSJSONSerialization,會把對應的資料轉換為NS類型的,NSDictionary,NSArray,NSString,NSNumber... ^(NSData *data,NSURLResponse *response,NSError *error) { NSDictionary *jsonObject = [NSJSONSerialization jsonObjectWithData:data tions:0 ror:nil]; } // 修改tableViewController - (void)viewDidLoad { [super viewDidLoad]; [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 0; return [self.courses count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { return nil; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath]; NSDictionary *course = self.courses[indexPath.row]; cell.textLabel.text = course[@"title"]; return cell; }7.主線程 Main Thread 現代蘋果裝置有多個處理器,所以可以存在多個程式碼片段並發執行。 主線程有時候也叫UI線程,與處理UI相關的都要放在主線程中。 然而像上面那種做法預設將NSURLSessionDataTask就放在其他線程中處理 background thread,****對比與上面做法的差異**** 載入完後reloadData,與UI相關,如何放到主線程中運行: dispatch_async函數 ^(NSData *data,NSURLResponse *response,NSError *error) { NSDictionary *jsonObject = [NSJSONSerialization jsonObjectWithData:data tions:0 ror:nil]; dispatch_async(dispatch_get_main_queue(),^{ [self.tableView reloadData]; }) }--------------------------------------------------------8.UIWebView 之前的每個儲存格資料保留了一個具體的url,點擊儲存格能顯示url的內容,但不需要離開應用去開啟safari // UIWebView 作為v存在一個viewController(c)中 @interface BNRWebViewController : UIViewController @property (nonatomic) NSUR *URL; @end @implementation BNRWebViewController -(void)loadView { UIWebView *webView = [[UIWebView alloc] init]; webView.scalePageToFit = YES; self.view = webView; } -(void)setURL:(NSURL *)URL { _URL = URL; if(_URL){ NSURLRequest *req = [NSURLRequest requestWithURL:_URL]; [(UIWenView *)self.view loadRequest:req]; } } @end ////// 在BNRCourseViewController.h中定義新屬性: @class BNRWebViewController; // 如果只是聲明,引入類即可 @property (nonatomic) BNRWebViewController *webViewController; @end////// 在delegation 中 -(BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options { //.....code. BNRWebViewController *wvc = [[BNRWebViewController alloc] init]; cvc.webViewController = wvc; }////// @implementation BNRCourseViewController -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSDictionary *course = self.courses[indexPath.row]; NSURL *url = [NSURL URLWithString:course[@"url"]]; self.webViewController.title = course[@"title"]; self.webViewController.URL = url; [self.navigationController pushViewController:self.webViewController animated:YES]; }9.認證 credentials 當你訪問一些網站,需要授權或者是身份認證等,就不能直接擷取資料,還需要中間提供驗證 //需要使用者名稱和密碼 -(void)fetchFeed { NNString *requestString = @"https://bookapi.bignerranch.com/private/courses.json"; //code... } -(instancetype) initWithStyle:(UITableViewStype)style { //code ... { //code ... _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; [self fetchFeed]; } return self; } ////// @implementation BNRCoursesViewController() <NSURLSessionDataDelegate> // delegation method -(void)URLSession:(NSURLSession *) session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition,NSURLCredential *)) completionHandler { NSURLCredential *cred = [NSURLCredential credentialWithUser:@"BigNerdRanch" password:@"AchieveNerdvana" persistence:NSURLCredentialPersistenceForSession completionHandler(NSURLSessionAuthChallengeUseCredential,cred)]; } @end10.UIWebView 會記錄瀏覽曆史,可以使用添加UIToolbar前進後退[goBack,goForward]
Big Nerd iOS Programming 第21章 Web service ,UIWebView