iOS程序访问服务器-实战篇二

本篇模拟对服务器返回xml数据以及json数据进行解析操作,获取指定值

  1. 运行apache
    sudo apachectl -k start
  2. xml文件
    http://localhost/xml.xml


  
    张鹏
    [email protected]
    一样菜
    985931
  
  
    王ss黑
    [email protected]
    冰封
    5625362
  
  
    阿顿
    [email protected]
    
    5625362
  
  
    王二
    [email protected]
    
    5625362
  
  
    王三三
    [email protected]
    
    5625362
  
  
    王海还
    [email protected]
    
    5625362
  

  1. iOS访问
//
//  ViewController.h
//  GETandPOST
//
//  Copyright © 2019 deerwang. All rights reserved.
//

#import 
#import "Student.h"

@interface ViewController : UITableViewController
@property (nonatomic, strong) NSArray *stuList;
- (IBAction)getFunc;
@end




//
//  ViewController.m
//  GETandPOST
//  Copyright © 2019 deerwang. All rights reserved.
//

#import "ViewController.h"


@interface ViewController () 

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self getFunc];
}

- (IBAction)getFunc {
    
    [self.refreshControl beginRefreshing];
}

//点击登录 触发get/post函数,获取网路请求;
-(IBAction)logClk:(id)sender {
    
    //[self getFunc];
}

-(void) setStuList:(NSArray *)stuList {
    _stuList = stuList;
    
    [self.tableView reloadData];
}

#pragma mark - 表格的数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.stuList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.创建cell
    static NSString *ID = @"CELL";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    // 2.设置cell的数据
    Student *student = self.stuList[indexPath.row];
    
    cell.textLabel.text = student.name;
    
    return cell;
}
@end


//DWXMLViewController是一个继承ViewController的子类
//
//  DWXMLViewController.h
//  GETandPOST
//
//  Copyright © 2019 deerwang. All rights reserved.
//

#import "ViewController.h"

NS_ASSUME_NONNULL_BEGIN

@interface DWXMLViewController : ViewController

@end

NS_ASSUME_NONNULL_END


//
//  DWXMLViewController.m
//  GETandPOST
//
//  Copyright © 2019 deerwang. All rights reserved.
//

#import "DWXMLViewController.h"

@interface DWXMLViewController () 
//xml
@property (nonatomic, strong) NSMutableArray *dataList;
@property (nonatomic, strong) NSMutableString *elementString;
@property (nonatomic, strong) Student *student;
@end

@implementation DWXMLViewController


#pragma makr 数据相关
- (IBAction)getFunc {
    [super getFunc];
    //登录完成前不能做其他操作
    //登录操作异步执行 不会影响到其他操作。
    NSString *str = [NSString stringWithFormat:@"http://localhost/xml.xml"];
    NSURL *urlStr = [NSURL URLWithString:str];
    
    //枚举类型参数cachePolicy为0 功能无效 效率更高。10s后超时
    NSURLRequest *request = [NSURLRequest requestWithURL:urlStr cachePolicy:0 timeoutInterval:10.0f];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError ) {
            NSLog(@"errpr: %@", connectionError.localizedDescription);
        } else {
            //将数据解析xml前的准备
            NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
            
            //设置代理
            parser.delegate = self;
            
            //开始解析
            [parser parse];
        }
    }];
    
    //外部登录不影响其他异步操作
    NSLog(@"main thread...");
}

#pragma mark -  NSXMLParserDelegate xml解析代理方法
#pragma mark 1.开始解析
- (void)parserDidStartDocument:(NSXMLParser *)parser {
    NSLog(@"开始解析文档");
    //拼接数组初始化
    if (!self.dataList) {
        self.dataList = [NSMutableArray array];
    } else {
        [self.dataList removeAllObjects];
    }
    
    //拼接字符串初始化
    if(!self.elementString) {
        self.elementString = [NSMutableString string];
    } else {
        //清空字符串的内容
        [self.elementString setString:@""];
    }
}

#pragma mark 2.开始节点
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    NSLog(@"开始节点:%@m %@", elementName, attributeDict);
    if([elementName isEqualToString:@"student"]) {
        self.student = [[Student alloc] init];
        self.student.stuId = (NSNumber *)attributeDict[@"stuId"];
    }
    //没开始一个新节点删除之前的elementString数据
    [self.elementString setString:@""];
}

#pragma mark 3.查找内容,重复调用多次
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    [self.elementString appendString:string];
    NSLog(@"%@", string);
}

#pragma mark 4.结束节点
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    NSLog(@"结束节点:%@", elementName);
    //判断 如果结尾是字段结束的标签 需要复制到对象当中
    if ([elementName isEqualToString:@"student"]) {
        [self.dataList addObject:self.student];
    } else if (![elementName isEqualToString:@"node"]) {  //只要结束 就对对象进行kvc赋值
        [self.student setValue:self.elementString forKey:elementName];
    }
}

#pragma mark 5.解析结束
- (void)parserDidEndDocument:(NSXMLParser *)parser {
    NSLog(@"文档解析完成");
    
    NSLog(@"%@", self.dataList);
    [self.dataList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSLog(@"---%@", obj);
    }];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        //将不可变赋值给可变类型加copy
        self.stuList = [self.dataList copy];
        [self.refreshControl endRefreshing];
    });
}

#pragma mark 6.解析报错
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    NSLog(@"error:%@", parseError.localizedDescription);
}

@end
  1. 其中getFunc函数是IBAction, 需要与refresh连线


    在这里插入图片描述

    加载的类需要更换一下


    在这里插入图片描述
  2. 运行结果:


    在这里插入图片描述

可以动态修改xml文件内容,然后下拉刷新更新展示

解析json数据, 同xml文件一样

  1. json.txt文件
[{"stuId": "1","name": "张鹏","email": "[email protected]","username": "一样菜","code": "985931"},{"stuId": "2","name": "王ss黑","email": "[email protected]","username": "冰封","code": "5625362"},{"stuId": "2","name": "王ss黑","email": "[email protected]","username": "冰封","code": "5625362"},{"stuId": "2","name": "王黑","email": "[email protected]","username": "冰封","code": "5625362"}]
  1. iOS访问,注意:
    NSURL *url = [NSURL URLWithString:@"http://localhost/json.txt"],这里的url也可以直接填写本地文件的路径
DWJSONViewController继承ViewController的子类
//
//  DWJSONViewController.m
//  GETandPOST
//
//  Copyright © 2019 deerwang. All rights reserved.
//

#import "DWJSONViewController.h"

@interface DWJSONViewController ()

@end

@implementation DWJSONViewController

- (void)getFunc
{
    // 显示刷新控件
    [super getFunc];
    
    // 1. URL
    NSURL *url = [NSURL URLWithString:@"http://localhost/json.txt"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:10];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            // 反序列化
            NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            
            // 建立数组
            NSMutableArray *arrayM = [NSMutableArray array];
            
            [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                Student *stu = [[Student alloc] init];
                
                [stu setValuesForKeysWithDictionary:obj];
                NSLog(@"%@", obj);
                
                [arrayM addObject:stu];
            }];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.stuList = [arrayM copy];
                
                [self.refreshControl endRefreshing];
            });
        } else {
            NSLog(@"error:%@", connectionError.localizedDescription);
        }
        
    }];
}

@end

你可能感兴趣的:(iOS程序访问服务器-实战篇二)