手动添加GDataXML方法(不使用pod的情况)
步骤:
核心代码:
#import "ViewController.h"
#import "GDataXMLNode.h"
#import "CDRelativeModel.h"
#import "CDDetailViewController.h"
@interface ViewController () <UITableViewDataSource , UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@end
@implementation ViewController{
NSMutableArray<CDRelativeModel *> *_dataArray;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.automaticallyAdjustsScrollViewInsets = NO;
//(黑客技)隐藏没有数据的单元格
_myTableView.tableFooterView = [[UIView alloc] init];
[self loadDataModel];
}
-(void) loadDataModel{
_dataArray = [NSMutableArray array];
//通过URL加载系统联网 - 基于http(s)联网系统
NSURL *url = [NSURL URLWithString:@"http://www.oschina.net/action/api/news_detail?id=77788"];
//创建POST请求
//可变请求NSMutableURLRequest
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
//修改请求命令
//req.HTTPMethod = @"POST";
//设置请求头参数
//[req setValue:@"参数" forHTTPHeaderField:@"参数名"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//NSLog(@"%@",data);
//解析XML
//1.SAX - 占内存少,事件驱动式解析 - 苹果原生
//2.DOM - 将整个文档作为一个对象加载到内存中,支持XPath查询语法,支持对节点的编辑操作 - 第三方
//options:预留参数,暂时没有任何作用
//error:错误对象
NSError *domError = nil;
GDataXMLDocument *dom = [[GDataXMLDocument alloc] initWithData:data options:0 error:&domError];
if (!error){
// "//relative":文档所有relative节点
// "/relative":只从根节点中找relative节点
NSArray *nodesArray = [dom nodesForXPath:@"//relative" error:nil];
[nodesArray enumerateObjectsUsingBlock:^(GDataXMLNode *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
CDRelativeModel *model = [[CDRelativeModel alloc] init];
GDataXMLNode *rtitle = obj.children[0];
model.title = rtitle.stringValue;
GDataXMLNode *rurl = obj.children[1];
model.urlStr = rurl.stringValue;
[_dataArray addObject:model];
//刷新界面
dispatch_async(dispatch_get_main_queue(), ^{
[_myTableView reloadData];
});
}];
}
}];
//启动任务
[task resume];
//默认GET请求
// [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//
// }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return _dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
CDRelativeModel *model = _dataArray[indexPath.row];
cell.textLabel.text = model.title;
return cell;
}
//使用StoryBoard连线方式跳转界面 -- 传值方法
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
//上个界面
//segue.sourceViewController
//要跳转的界面
//segue.destinationViewController
CDDetailViewController *detailVC = segue.destinationViewController;
detailVC.urlStr = _dataArray[_myTableView.indexPathForSelectedRow.row].urlStr;
}
@end
网友评论