Xcode 代码片段

AFNetworking

2019-07-17  本文已影响0人  _YN

如果您在阅读我的文章时有疑问 , 请点击这里

//创建管理者
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    // 告诉AFN,支持接受 text/xml 的数据
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
//json
    manager.responseSerializer = [AFJSONResponseSerializer serializer];

    /**
    
        开始写请求参数
     NSDictionary *dic=[值:参数名称];
     把 dic 放到 parameters 里
     例子:
     [manager GET:@"" parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
     
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
     
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
     
     }];
     同理,Post 也放在相同的地方
     
     */
//
     //Get
    [manager GET:@"" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    // Post
    [manager POST:@"" parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

get 和 psot

- (IBAction)GET:(id)sender {
    //创建数据请求管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //这是关闭它的自动解析功能
    //mannage.responseSerializer = [AFHTTPResponseSerializer serializer];
    //添加的支持的解析类型@"text/html",
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    //GET 接口
    [manager GET:JSON_URL parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //数据请求的成功回调
        NSLog(@"//////////%@",responseObject);

        for (NSDictionary *dic in responseObject[@"category"]) {
            MyModel *model = [MyModel new];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataSoure addObject:model];
        }
        //重要的一点   主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //数据请求失败的回调
        NSLog(@"//////////%@",error);
    }];
}
- (IBAction)POST:(id)sender {
    //
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //拼接参数
    NSDictionary *dic = @{@"methodName":@"Homeindex"};

    [manager POST:PATH parameters:dic headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);

        for (NSDictionary *dic in responseObject[@"category"]) {
            MyModel *model = [MyModel new];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataSoure addObject:model];
        }
        //重要的一点   主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}
- (IBAction)Moniter:(id)sender {
    //做一个网络状态监听
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        /*
         AFNetworkReachabilityStatusUnknown          = -1,
         AFNetworkReachabilityStatusNotReachable     = 0,
         AFNetworkReachabilityStatusReachableViaWWAN = 1,
         AFNetworkReachabilityStatusReachableViaWiFi = 2,
         */
        NSLog(@"%ld",(long)status);
    }];
    //开始监听
    [manager.reachabilityManager startMonitoring];
    //停止监听

}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSoure.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    }
    if (self.dataSoure.count > 0 ){
        MyModel *model = _dataSoure[indexPath.row];
        cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"category_%@.ipg",model.categoryName]];
        cell.textLabel.text = model.categoryName;
        cell.detailTextLabel.text  = [NSString stringWithFormat:@"一共有%@款应用 , 其中%@款限免",model.count,model.lessenPrice];

    }



    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

请求为一个表格

#import "ViewController.h"
#import "MyModel.h"
#import "AFNetworking.h"
#import "Two.h"
#define get_666 "http://d.yixincao.com/interface/getdata.php?act=list&type=nuanwen&page=0"
@interface ViewController ()<UITableViewDelegate , UITableViewDataSource>
{
    UITableView *tbv;
    NSMutableArray *dataSoure;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    tbv = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    tbv.delegate = self;
    tbv.dataSource = self;
    [self.view addSubview:tbv];
    dataSoure = [NSMutableArray new];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [manager GET:@get_666 parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //成功返回
        NSLog(@"///成功////%@",responseObject);

        for (NSDictionary *dic in responseObject[@"data"]) {
            MyModel *model  = [MyModel new];
            model.author = [dic objectForKey:@"author"];
            model.pic = [dic objectForKey:@"pic"];
            model.title = [dic objectForKey:@"title"];
            model.sid = [dic objectForKey:@"id"] ;
            [self->dataSoure addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{

            [self->tbv reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //失败返回
        NSLog(@"////失败////%@",error);
    }];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataSoure.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];

        MyModel *model = dataSoure[indexPath.row];
        cell.imageView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dataSoure[indexPath.row]pic]]]];
        cell.textLabel.text = model.title;
        cell.textLabel.lineBreakMode = UILineBreakModeCharacterWrap;
        cell.textLabel.numberOfLines = 0;
        UILabel *zuozhe = [[UILabel alloc] initWithFrame:CGRectMake(300, 50, 100, 40 )];
        zuozhe.text = model.author;
        [cell addSubview:zuozhe];



    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    Two *two =[[Two alloc] init];
//    NSLog(@"%@",[dataSoure[indexPath.row]sid]);
    two.twoID = [dataSoure[indexPath.row]sid];
    [self.navigationController pushViewController:two animated:YES];
}
@end
上一篇 下一篇

猜你喜欢

热点阅读