欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS Objective-C 获取api数据

程序员文章站 2022-03-08 15:49:53
NSURLSessionGETPOST- (void)getDataWithPostSession { NSURLSession *session = [NSURLSession sharedSession]; NSURL *url = [NSURL URLWithString:@"https://xxxxxx/"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; req...

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文件:
iOS Objective-C 获取api数据

本文地址:https://blog.csdn.net/cungudafa/article/details/111357177