Big Nerd iOS Programming 第21章 Web service ,UIWebView

1.
    兩部分:
        連接並獲取數據
        從獲取到數據構建數據模型
2.經過HTTP協議於web服務器通訊
    `瀏覽器發送一個請求給制定的url地址,url返回求情頁。HTML以及圖片
    `瀏覽器發生帶有其餘參數的好比是表數據 給制定的服務器,服務器返回一個自定義的或者動態的活着web page
3.數據格式通常是JSON或者XML

4.請求的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建立dataTask

6.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)];
        }

    @end


10.UIWebView 會記錄瀏覽歷史,可使用添加UIToolbar前進後退[goBack,goForward]
相關文章
相關標籤/搜索