NLRMashapeClientMashape API 调用

联合创作 · 2023-09-27

NLRMashapeClient 基于 AFNetworking 构建,NLRMashapeClient 提供简单和方便的形式来调用你在 Mashape 选择的 APIs。

用法

“ Ultimate Weather Forecasts”为例,这是一个免费的返回天气状况的API。登录到Mashape并拥有至少一个应用程序后,将为Mashape Key每个应用程序获得一个,以提出对此应用程序的请求。

首先,创建NLRMashapeClient的子类,并声明单例方法,如下所示。

#import "NLRMashapeClient.h"

@interface WeatherClient : NLRMashapeClient

+ (instancetype)sharedClient;

@end

现在,应该使用正确的API名称和Mashape App Key实现单例方法。API名称是URL中位于之前的部分.p.mashape.com。例如,如果天气API的基本网址为https://george-vustrey-weather.p.mashape.com,则应使用george-vustrey-weather。可以从Mashape的应用程序页面中获取应用程序密钥,然后按“获取密钥”按钮。


#import "WeatherClient.h"

@implementation WeatherClient

+ (instancetype)sharedClient
{
    static dispatch_once_t once;
    static id sharedInstance;

    dispatch_once(&once, ^{
        sharedInstance = [[self alloc]  initWithAPIName:@"george-vustrey-weather" mashapeAppKey:@"THE-KEY-FOR-YOUR-APP"];
    });

    return sharedInstance;
}

@end

对于将使用的每个Mashape API,应该使用的一个子类/单个子类NLRMashapeClient

正确初始化客户端后,就可以完成配置,并且可以进行任意数量的调用,而无需设置标题,键,而仅需注意:端点和参数!

例如,如果示例GEThttps://george-vustrey-weather.p.mashape.com/api.php,而参数为location,则只需调用:

    [[WeatherClient sharedClient]] GET:@"api.php" parameters:@{@"location" : @"Tel Aviv"} success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@", responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];

对于单个调用,Mashape提供的Objective-C示例要简单得多。

如果想更多地玩这个游戏,可以使用示例项目(它需要CocoaPods并在运行pod install之前运行)。

浏览 5
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报