iOS Objective-C 获取api数据

转:

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>
上一篇:C#参考篇 第10部分 C#预处理指令


下一篇:MySQL案例:binlog_row_image如何取舍