前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ios网络编程学习

ios网络编程学习

作者头像
tandaxia
发布2018-09-27 12:25:08
7670
发布2018-09-27 12:25:08
举报
文章被收录于专栏:谈补锅
代码语言:javascript
复制
//网络访问获取数据
//定义一个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);
        }
    });
}
代码语言:javascript
复制
/**
 *  使用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

代码语言:javascript
复制
/**
 *  使用系统自带库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数据的基本思路是,在元素开始时创建一个空对象,找到内容时,读取内容并为对象的属性赋值,元素结束时将对象添加到集合中。

 示例代码:

代码语言:javascript
复制
//创建一个Customer类
@interface Customer : NSObject

@property (nonatomic, assign) int cid;  //客户id
@property (nonatomic, retain) NSString *name;//客户姓名
@property (nonatomic, assign) int age;  //客户年龄

@end
代码语言:javascript
复制
//先定义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];
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015-03-07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云服务器
云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档