网络:XML 解析(使用GDataXMLNode第三方框架)

来源:互联网 发布:mac罗马数字怎么打 编辑:程序博客网 时间:2024/05/16 05:12
#import "ViewController.h"#import "CZVideo.h"//#import "CZParseVideoXml.h"#import "CZVideoCell.h"#import "GDataXMLNode.h"@interface ViewController ()<NSXMLParserDelegate>@property (nonatomic, strong) NSArray *data; // 数组数据@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    [self loadData];    [self setupRefresh];}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {    return self.data.count;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    CZVideoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CZVideoCell" forIndexPath:indexPath];    // 设置行对应的数据    cell.video = self.data[indexPath.row];    return cell;}// 初始化刷新控件- (void)setupRefresh {    self.refreshControl = [[UIRefreshControl alloc]init];    // 添加事件    [self.refreshControl addTarget:self action:@selector(loadData) forControlEvents:UIControlEventValueChanged];    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc]initWithString:@"正在玩命加载中..." attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18],NSForegroundColorAttributeName:[UIColor redColor]}];    // 设置标题    self.refreshControl.attributedTitle = attributeStr;//    self.refreshControl.tintColor = [UIColor redColor];}// xml 解析都是一个模型一个解析文件- (IBAction)loadData {    // NSURL    NSURL *url = [NSURL URLWithString:@"http://localhost/videos.xml"];    // 创建请求    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:15];    // 异步发送请求    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {        GDataXMLDocument *xml = [[GDataXMLDocument alloc]initWithData:data error:nil];        NSMutableArray *dataM = [NSMutableArray array];        // 根节点        GDataXMLElement *root = xml.rootElement;        [root.children enumerateObjectsUsingBlock:^(GDataXMLElement *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {            // 创建模型            CZVideo *video = [[CZVideo alloc]init];//            NSLog(@"%@",obj.attributes);            video.videoId = @([[[obj.attributes lastObject] stringValue] integerValue]);            [dataM addObject:video];            // video            [obj.children enumerateObjectsUsingBlock:^(GDataXMLElement *  _Nonnull objChildren, NSUInteger idx, BOOL * _Nonnull stop) {                // name/length/...//                NSLog(@"%@",objChildren.stringValue);                NSString *key = objChildren.name;                NSString *value = objChildren.stringValue;                [video setValue:value forKey:key];            }];        }];        self.data = dataM.copy;        [self.tableView reloadData];        NSLog(@"%@",self.data);    }];}@end
0 0
原创粉丝点击