iOS Objective-C 获取api数据

NSURLSession

直接用session获取

- (void)getDataWithPostSession {
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:@"https://xxxxxx/"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";//方式
    
    request.HTTPBody = [NSJSONSerialization dataWithJSONObject:@{@"query":@{@"key":@"top"}} options:nil error:nil];//请求内容
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //NSLog(@"%@",response);
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];//转为json格式
        NSLog(@"%@",dic);
        if (error) {
            NSLog(@"%@",error);
        }
    }];
    [dataTask resume];
}

AFNetworking

通过第三方库来获取资源

pod安装AFNetworking

#import "AFNetworking.h"

[self AFNetGetDataWithPath:@"https://xxxxxx.com/" andParameters:@{@"query":@{}}];

-(void)AFNetGetDataWithPath:(NSString *)path andParameters:(NSDictionary *)dic{
    AFHTTPSessionManager* session = [AFHTTPSessionManager manager];//创建会话管理器对象
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];//json类型
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    [session POST:path parameters:dic headers:@{@"Content-Type":@"application/json"} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功了success %@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败了error %@",error);
    }];

}

以上都是POST请求,如果是Get对应修改即可,相应的请求参数配置在Parameters中。

附:
获取到的内容多是JSON格式,文本内容;
如果想要转换为model模型,这里可以安装第三方库:YYModel

#import "YYModel.h"
#import "testModel.h"//模型

testModel *model = [testModel yy_modelWithJSON:self.data];
NSLog(@"直接调用model的属性%@",model.name);

如果要获取网络图片,需要安装第三方库:SDWebImage

#import <UIImageView+WebCache.h>

[self.imageView sd_setImageWithURL:[NSURL URLWithString:@"https://xxxxxx/xx.png"]];

相关pod文件:
在这里插入图片描述

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值