ios網路編程學習

來源:互聯網
上載者:User

標籤:

//網路訪問擷取資料
//定義一個UIWebView屬性,用來展示資料@property (strong, nonatomic) IBOutlet UIWebView *myWebView;//.......//使用NSURLConnection發送非同步請求擷取資料- (void)getData:(id)sender{ //訪問的網站地址 NSString *str = @"http://www.apple.com/"; //執行個體化NSURL對象 NSURL *url = [NSURL URLWithString:str]; //執行個體化NSURLRequest對象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //執行個體化操作隊列 NSOperationQueue *queue = [[NSOperationQueue alloc] init]; //發送非同步請求 [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) { //獲得網路抓取的資料 if ([data length] > 0 && error == nil){ //將NSData轉換為NSString NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; //使用UIWebView顯示網頁 [self.myWebView loadHTMLString:html baseURL:nil]; NSLog(@"html = %@", html); } }];}/*使用NSUrlConnection發送同步請求獲得資料 使用同步請求的時候,最好在單獨的一個線程中進行, 這樣可以避免程式阻塞 */- (void)getDataTwo:(id)sender{ //全域隊列 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //非同步並行隊列,開闢一個新線程 dispatch_async(queue, ^{ NSURL *url = [NSURL URLWithString:@"http://www.apple.com"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSURLResponse *response; NSError *error; //NSURLConnection發送同步請求,獲得資料 NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; //判斷結果 if ([data length] > 0 && error == nil){ NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"html = %@", html); } });}

  

/** *  使用NSMutableURLRequest向伺服器發送POST請求擷取資料 */- (void)getDataThree:(id)sender{    //建立一個線程    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);    //執行非同步任務    dispatch_async(queue, ^{       //擷取新浪的天氣預報資訊網址        //http://php.weather.sina.com.cn/xml.php?city=%B1%B1%BE%A9&password=DJOYnieT8234jlsK&day=0                //在block中從網路擷取資料        NSString *str = @"http://php.weather.sina.com.cn/xml.php";        //建立NSURL對象        NSURL *url = [NSURL URLWithString:str];        //可變URL請求        NSMutableURLRequest *mRequest = [[NSMutableURLRequest alloc] init];        //為請求設定URL        [mRequest setURL:url];        //佈建要求逾時時間        [mRequest setTimeoutInterval:10];        //佈建要求方法為post        [mRequest setHTTPMethod:@"POST"];        //body內容        NSString *body = @"city=%B1%B1%BE%A9&password=DJOYnieT8234jlsK&day=0";        //設定body        [mRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];                //獲得響應        NSURLResponse *response;        NSError *error;        //獲得返回資料        NSData *data = [NSURLConnection sendSynchronousRequest:mRequest returningResponse:&response error:&error];        //將NSData轉換成字串        NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];                //使用UIWebView載入資料        [self.myWebView loadHTMLString:content baseURL:nil];        //輸出結果        NSLog(@"content = %@", content);            });}

  

資料解析

在網路編程中,從伺服器擷取的資料格式大致分為兩種:JSON和XML。其中JSON作為一種輕量級的資料交換格式,正在逐步取代XML, 成為網路資料的通用格式。

測試列子:調用一個天氣預報的API, 地址是:http://m.weather.com.cn/data/101010100.html

/** *  使用系統內建庫NSJSONSerialization解析json資料    訪問http://m.weather.com.cn/data/101010100.html ,返回結果為: {"weatherinfo":{"city":"北京","city_en":"beijing","date_y":"2014年3月4日","date":"","week":"星期二","fchh":"11","cityid":"101010100","temp1":"8℃~-3℃","temp2":"8℃~-3℃","temp3":"7℃~-3℃","temp4":"8℃~-1℃","temp5":"10℃~1℃","temp6":"10℃~2℃","tempF1":"46.4℉~26.6℉","tempF2":"46.4℉~26.6℉","tempF3":"44.6℉~26.6℉","tempF4":"46.4℉~30.2℉","tempF5":"50℉~33.8℉","tempF6":"50℉~35.6℉","weather1":"晴","weather2":"晴","weather3":"晴","weather4":"晴轉多雲","weather5":"多雲","weather6":"多雲","img1":"0","img2":"99","img3":"0","img4":"99","img5":"0","img6":"99","img7":"0","img8":"1","img9":"1","img10":"99","img11":"1","img12":"99","img_single":"0","img_title1":"晴","img_title2":"晴","img_title3":"晴","img_title4":"晴","img_title5":"晴","img_title6":"晴","img_title7":"晴","img_title8":"多雲","img_title9":"多雲","img_title10":"多雲","img_title11":"多雲","img_title12":"多雲","img_title_single":"晴","wind1":"北風4-5級轉微風","wind2":"微風","wind3":"微風","wind4":"微風","wind5":"微風","wind6":"微風","fx1":"北風","fx2":"微風","fl1":"4-5級轉小於3級","fl2":"小於3級","fl3":"小於3級","fl4":"小於3級","fl5":"小於3級","fl6":"小於3級","index":"寒冷","index_d":"天氣寒冷,建議著厚羽絨服、毛皮大衣加厚毛衣等隆冬服裝。年老體弱者尤其要注意保暖防凍。","index48":"冷","index48_d":"天氣冷,建議著棉服、羽絨服、皮夾克加羊毛衫等冬季服裝。年老體弱者宜著厚棉衣、冬大衣或厚羽絨服。","index_uv":"中等","index48_uv":"中等","index_xc":"較適宜","index_tr":"一般","index_co":"較舒適","st1":"7","st2":"-3","st3":"8","st4":"0","st5":"7","st6":"-1","index_cl":"較不宜","index_ls":"基本適宜","index_ag":"易發"}} */- (void)getWeatherData:(id)sender{    NSURL *url = [NSURL URLWithString:@"http://m.weather.com.cn/data/101010100.html"];    NSURLRequest *requst = [NSURLRequest requestWithURL:url];        //發送非同步請求    [NSURLConnection sendAsynchronousRequest:requst queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {                if ([data length] > 0 && error == nil){            //將NSData轉換成NSDictionary            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];            //結果為字典中有字典,獲得key為weatherinfo的字典            NSDictionary *dic2 = [dic objectForKey:@"weatherinfo"];            //遍曆字典            for (NSString *key in dic2) {                NSLog(@"%@:%@", key, [dic2 objectForKey:key]);            }        }    }];}

  

XML解析可以通過蘋果內建的API -> NSXMLParser和其代理類NSXMLParserDelegate。

NSXMLParseDelegate代理類中有一組方法用來檢測文檔的讀取狀態,例如,文檔開始、文檔結束、元素開始、元素結束、內容開始等;

解析XML資料的基本思路是,在元素開始時建立一個Null 物件,找到內容時,讀取內容並為對象的屬性賦值,元素結束時將對象添加到集合中。

 範例程式碼:

//建立一個Customer類@interface Customer : NSObject@property (nonatomic, assign) int cid;  //客戶id@property (nonatomic, retain) NSString *name;//客戶姓名@property (nonatomic, assign) int age;  //客戶年齡@end

  

//先定義4個屬性@property (nonatomic, retain) Customer *customer;   //客戶執行個體@property (nonatomic, retain) NSXMLParser *parser;  //xml解析器@property (nonatomic, retain) NSMutableArray *array;    //可變數組@property (nonatomic, strong) NSString *currrentElement;    //當前元素//初始化方法- (void)initParser{   //初始化數組,用來容納客戶對象    self.array = [NSMutableArray arrayWithCapacity:10];    //獲得客戶XML檔案的URL路徑    NSString *str = [[NSBundle mainBundle] pathForResource:@"customers" ofType:@"xml"];    //將客戶XML轉換成NSData    NSData *data = [[NSData alloc] initWithContentsOfFile:str];    //執行個體化XML解析器    self.parser = [[NSXMLParser alloc] initWithData:data];    //設定代理    self.parser.delegate = self;}/** *  實現協議代理方法 *///讀文檔開始- (void)parserDidStartDocument:(NSXMLParser *)parser{    NSLog(@"parserDidStartDocument...");}//讀文檔結束- (void)parserDidEndDocument:(NSXMLParser *)parser{    NSLog(@"parserDidEndDocument....");}//讀元素開始- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{    NSLog(@"didStartElement...");    self.currrentElement = elementName;    if ([self.currrentElement isEqualToString:@"customer"]){        self.customer = [[Customer alloc] init];    }}//找到內容- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{    NSLog(@"foundCharacters....");        if ([self.currrentElement isEqualToString:@"id"]){        int cid = [string integerValue];        [self.customer setCid:cid];    }    else if ([self.currrentElement isEqualToString:@"name"]){        [self.customer setName:string];    }    else if ([self.currrentElement isEqualToString:@"age"]){        [self.customer setAge:[string integerValue]];    }}//讀元素結束- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{    NSLog(@"didEndElement...");        if ([elementName isEqualToString:@"customer"]){        [self.array addObject:self.customer];    }    self.currrentElement = nil;}//開始解析方法- (void)parse:(id)sender{    //刪除數組中的所有資料    [self.array removeAllObjects];    //開始解析    [self.parser parse];    //獲得數組大小    NSInteger count = [self.array count];}

  

 

ios網路編程學習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.