调用 Mashape API 的简单方法
当调用通过 Mashape 提供的一些 API 时,您可以使用他们提供的请求示例。问题在于,大多数开发者(至少我是)比 Unirest for Objective-C 更熟悉 AFNetworking,而不是示例中所用的 Unirest。不仅如此,还有
成功
/失败
回调和 AFHTTPSessionManager
以及整个 AFNetworking
的结构都要好得多。因此,我决定在 AFNetworking
的基础上构建一个 Mashape 客户端。
以 "终极天气预测" 为例,这是一个返回天气条件的免费 API。登录 Mashape 并至少有一个应用程序后,您将为每个应用程序获得一个 Mashape 密钥
,以便为该应用程序发出请求。
首先,创建 NLRMashapeClient 的子类,并声明如下单例方法。
#import "NLRMashapeClient.h"
@interface WeatherClient : NLRMashapeClient
+ (instancetype)sharedClient;
@end
现在,您应该实现单例方法,使用正确的 API 名称和 Mashape App Key。API 名称是 URL 中的部分,在 .p.mashape.com
之前。例如,如果天气 API 的基本 URL 是 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
的子类/单例。
您的客户端初始化正确后,配置就完成了,您可以根据需要发出尽可能多的调用,而无需设置头部、密钥,只需关注:端点和参数!
例如,如果“GET”示例是 https://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 示例要简单得多。但是,如果您需要发出多个调用,希望将参数传递到字典中,希望使用 NSURLSession
,并且熟悉 AFNetworking
,那么这就是为您准备的!!
如果您想更多地使用这个项目,您可以直接使用示例项目(需要 CocoaPods,运行前请先执行 pod install
)。
当然,使用 NLRMashapeClient
的最佳方式是结合 CocoaPods。
在您的 Podfile 中添加以下行
pod 'NLRMashapeClient', '~> 0.1'