网络连接和数据解析

网络连接和数据解析

[TOC]

第三方库介绍

一切第三方库的使用都在README

MBProgressHUD

弹出的提示只需设置一定的时间自动消失,苹果原生的需要用户点击确定才取消是糟糕的体验。

弹出消息提示Demo

@interface CDUtility : NSObject

/**显示提示信息*/
+ (void) showHintMsg:(NSString *) message onView:(UIView *) view;

#import "CDUtility.h"
#import "MBProgressHUD.h"

@implementation CDUtility

+ (void)showHintMsg:(NSString *) message onView:(UIView *) view{
    NSOperation *op = [NSBlockOperation blockOperationWithBlock:^{
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = message;
        // 设置延迟的时间
        [hud hide:YES afterDelay:1];
    }];
    [[NSOperationQueue mainQueue] addOperation:op];
}

@end

YYModel

解析数据必备神器

  • 属性映射:modelCustomPropertyMapper
  • 类名映射:modelContainerPropertyGenericClass
  • 解析字典:yy_modelWithDictionary(字典转换成模型)

属性和类不对应时的映射Demo

 // 属性和JSON数据映射
+ (NSDictionary *)modelCustomPropertyMapper
{
    // ID是后面返回的值,自己的定义,映射的是id
    return @{@"ID": @"id"};
}

// 属性和类关联映射
+ (NSDictionary *)modelContainerPropertyGenericClass
{
    // 同样是前一个映射后一个
    return @{@"relativies" : [RelativiesModel class]};
}

下拉刷新原理和MJRefresh使用

  • 简单的刷新下拉刷新,触底加载需要用scrollViewDidScroll去定制计算。

苹果原生TableViewFreshDemo

UIRefreshControl *_ref;
  // 必须要tableView创建以后
    _ref = [[UIRefreshControl alloc] init];
    _ref.tintColor = [UIColor redColor];
    [_ref addTarget:self action:@selector(loadData) forControlEvents:UIControlEventValueChanged];
    [myTableView addSubview:_ref];
    
    // 拿到新数据后要在结束刷新的时候在删除原来的数据
        //[_ref endRefreshing];
        // 移除原来的数据
        [_dataArray removeAllObjects];

MJRefresh

  • 下拉刷新和触底加载footer和header属性,beginFresh和endFresh。

AFNetworking

emsp;联网请求工具

步骤

1.AFHTTPSessionManager
2.manager.responseSerializer.acceptableContentTypes
3.manager:GET:parameters:success:failure

2.5.4版本AFNetworking和MJRefresh

- (void) loadData
{
    if (!dataArray) {
        dataArray = [NSMutableArray array];
    }
    // 创建一个HTTP会话管理器
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 提示: AFNetworking默认只接受JSON格式的数据
    // 很多服务器返回的是JSON格式的数据但MIME类型设置成text/html
    // 为了让AFNetworking能够处理非JSON的MIME类型
    // 要指定会话管理器的responseSerializer属性可接受内容的类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    // 通过会话管理器发出GET请求
    // 第一个参数: 统一资源定位符的字符串
    // 第二个参数: 发给服务器的HTTP请求参数
    // 第三个参数: 请求成功要回调的Block
    // 第四个参数: 请求失败要回调的Block
    [manager GET:[NSString stringWithFormat:@"%@%@",kBaseURL,kAlbumListURL] parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        // 拿到新数据后要在结束刷新的时候在删除原来的数据
        //[_ref endRefreshing];
        // 移除原来的数据
        [myTableView.header endRefreshing];
        [myTableView.footer endRefreshing];
        [dataArray removeAllObjects];
        
        [responseObject[@"albums"] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            LXKAlbumModel *model = [LXKAlbumModel yy_modelWithDictionary:obj];
            [dataArray addObject:model];
        }];
        [myTableView reloadData];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        // 联网失败也需要结束刷新数据
        //[_ref endRefreshing];
        [myTableView.header endRefreshing];
        [myTableView.footer endRefreshing];
        NSLog(@"%@",error);
    }];

SDWebImage加载图片

  • sd_setImageWithURL
 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",kBaseURL2,model.pic]];
    NSLog(@"%@",url);
    [photoImageView sd_setImageWithURL:url];

苹果原生联网iOS8请求

其实我用着觉得很爽,感觉很有调理性

三个步骤

  • NSURL
  • NSURLSession
  • NSURLSession shareSession
  • 也可以通过NSURLSessionConfiguration来写单例配置环境,请求策略,时间等等。
  • NSURLSessionDataTask
  • session dataTaskWithURL:CompletionHandler:

Demo


    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://10.0.8.8/sns/my/create_album.php?albumname=%@&privacy=0",[name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSDictionary *dict  = [NSJSONSerialization JSONObjectWithData:data options:1 error:nil];
            if ([dict[@"code"] isEqualToString:@"do_success"]) {
                LXKAlbumModel *model = [[LXKAlbumModel alloc] init];
                model.albumname = name;
                model.pics = 0;
                model.albumId = dict[@"albumid"];
                [dataArray insertObject:model atIndex:0];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [myTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationRight];
                });
            }
        }
        else {
            NSLog(@"%@",error);
        }
    }];
    
    [task resume];

你可能感兴趣的:(网络连接和数据解析)