ios网络编程学习

//网络访问获取数据
//定义一个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数据的基本思路是,在元素开始时创建一个空对象,找到内容时,读取内容并为对象的属性赋值,元素结束时将对象添加到集合中。

 示例代码:

//创建一个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];
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏前端说吧

JS:“分享到”之类的悬浮框的运动原理(代码)

43870
来自专栏流浪猫的golang

MongoDB 中文的全文索引

MongoDB 从3.2 版本以后添加了对中文索引的支持: 官网链接:https://docs.mongodb.com/manual/reference/t...

43930
来自专栏DannyHoo的专栏

iOS中将颜色转为图片

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010105969/article/details/...

11420
来自专栏岑志军的专栏

ReactNative-ListView

21630
来自专栏菩提树下的杨过

ExtJs学习笔记(3)_GridPanel[XML做数据源]

这一节,将学习到除了用JSON做GridPanel的数据源外,还可以使用XML 一。静态示例 1.xml文件内容: <?xml version="1.0...

24680
来自专栏图形学与OpenGL

9.3.3编程实例-图形拾取

int select_point = 0; //1 是第一个点,2是第二个,以此类推

14640
来自专栏Android干货

Android项目实战(二十九):酒店预定日期选择

28840
来自专栏Hongten

pygame系列_箭刺Elephant游戏_源码下载

http://www.pygame.org/docs/tut/chimp/ChimpLineByLine.html

20740
来自专栏哈雷彗星撞地球

iOS 中获取某个视图的截图

最近在做SDK的截图,想触发类似系统的截屏功能,找了一圈,总结一下靠谱的几种方式。 我写了个UIView 的category,将这几种方式封装和简化了一下。

25930
来自专栏ios 技术积累

MJRefresh 封装

MJRefresh是很好用的一个刷新控件,但是如果在每个ViewController中都加入如下代码

33020

扫码关注云+社区

领取腾讯云代金券