iOS之網路資料下載和Json資料解析,iosjson資料解析

來源:互聯網
上載者:User

iOS之網路資料下載和Json資料解析,iosjson資料解析
iOS之網路資料下載和Json資料解析簡介

  在本文中筆者將要給大家介紹iOS中如何利用NSURLConnection從網路上下載資料,如何解析下載下來的JSON資料,以及如何顯示資料和圖片的非同步下載顯示

  涉及到的知識點:

  1.NSURLConnection非同步下載封裝

  2.JSON格式和JSON格式解析

  3.資料顯示和使用SDWebImage非同步顯示圖片

內容1.網路下載基礎知識介紹

 

(1)什麼是網路應用?

  一般情況下, iPhone的電腦, 照相機不需要從網路上下載資料也能運行, 所以這種類型的應用是本地應用, 但是iPhone上絕大多數的應用都需要網路才能運行, 例如QQ, , 蝦米音樂, 所以在iOS開發中需要知道如何從網路上下載資料

 

  (2)網路應用的程式結構

  網路應用不同於本地應用, 網路應用的資料是從網路上下載下來的, 所以需要在網路上運行一個程式為應用提供資料, 或者提供服務, 那麼這個網路應用一般稱為用戶端, 而網路上啟動並執行服務稱為服務端

 

  (3)常見的網路介面形式

  iOS網路應用常見的資料介面一半都是HTTP形式的URL地址, 例如愛限免應用首頁的資料地址為http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id=

  在項目中一般使用一些開源庫通過這種網址下載資料. 例如AFNetworking

 

  (4)常見的資料格式

  iOS開發中常見的資料格式有兩種, 一種是JSON格式, 另外種是XML格式, 相對來說, JSON格式使用的比較多

 

  (5)介面開發的一般流程

    iOS中開發一個介面, 需要介面, 介面素材資源, 和網路介面

    開發的流程一般如下所示

    ***1, 下載資料

    ***2, 解析JSON或XML資料, 建立資料模型model

    ***3, 使用控制項顯示資料, 必要的時候定製視圖, 例如定製cell

2.NSURLConnection使用

 

NSURLConnection非同步下載和同步下載,NSString同步下載

#pragma mark - NSURLConnection非同步下載-(void)testNSURLConnectionAsyncDownloadData{    NSString *urlString = @"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id=";        //初始化    _data = [[NSMutableData alloc] init];    //發起了一個非同步URL串連請求    //非同步:   執行了方法之後開始下載,立即返回    //              下載過程在後台(多線程)執行    _connection = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] delegate:self startImmediately:YES];    NSLog(@"initWithRequest 執行完成");    }//代理方法: 接收到伺服器響應執行-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{    NSLog(@"接收到伺服器響應執行");}//代理方法: 接收到資料的時候執行//注意: 當資料比較大, 可能多次執行-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{        [_data appendData:data];}//代理方法: 資料下載完成了-(void)connectionDidFinishLoading:(NSURLConnection *)connection{    //NSString *str = [[NSString alloc] initWithData:_data encoding:NSUTF8StringEncoding];    //NSLog(@"str = %@",str);        //最簡單: 顯示所有應用程式名稱字    //解析JSON    //作用: JSON資料轉化為NSArray或NSDictionary    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingMutableContainers error:nil];    //NSLog(@"dict = %@",dict);        //NSArray *appList = dict[@"applications"];    NSArray *appList = [dict valueForKey:@"applications"];    for (NSDictionary *appDict in appList) {        NSLog(@"name = %@",appDict[@"name"]);    }                //NSArray *a = @[@"test",@"vec"];    //NSDictionary *d = @{@"k1":@"v1",@"k2":@"v2"};    //NSLog(@"v = %@",d[@"k1"]);        }-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{    NSLog(@"error = %@",error);}#pragma mark - NSURLConnection同步下載-(void)testNSURLConnectionSyncDownloadData{    NSString *urlString = @"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id=";        //發送同步URL請求    //NSURLRequest URL請求對象    NSURL *url = [NSURL URLWithString:urlString];    NSURLRequest *request = [NSURLRequest requestWithURL:url];    NSError *error = nil;    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];    if(error == nil)    {        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];        NSLog(@"str = %@",str);    }    else    {        NSLog(@"下載失敗");    }    }#pragma mark - NSString同步下載-(void)testNSStringDownloadData{    // HTTP中使用URL地址    //  http:// 地址使用協議(ftp://)    //  iappfree.candou.com  主機地址(網域名稱和IP)    //  :8080                   主機連接埠    //  /free/applications/limited  網頁程式檔案路徑    //  ?currency=rmb&page=1&category_id= 程式參數(參數用&分割)        NSString *urlString = @"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id=";        //下載資料    //通過地址產生NSURL對象    NSError *error = nil;    NSURL *url = [NSURL URLWithString:urlString];    NSString *content = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];    if (error==nil) {        NSLog(@"content = %@",content);    }    else    {        NSLog(@"下載失敗");    }        //項目中怎麼使用    //1.同步形式下載, initWithContentsOfURL下載完了之後才會返回    //      造成介面假死,不能用    //2.使用非同步下載(NSURLConnection非同步下載)    }
3.JSON格式說明和格式化工具
//JSON    //JavaScript Object Notation        /*    {        "count":20,        "data":[            "zhangsan",            "lisi",            "wangwu"        ]    }    */    //[]    表示數組,對應NSArray    //,     表示並列的資料    //{}    表示字典,對應NSDictionary    //:     表示索引值對    //"ta"  表示字串,對應NSString    //20    對應NSNumber        //JSON格式格式化工具    //  Jason    //  Json Editor    //  線上:  http://www.kjson.com/

 

4.一個完整頁面的實現(包括model的建立,SDWebImage的使用)

 :

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.