NLRMashapeClientMashape API 調用
NLRMashapeClient 基于 AFNetworking 構建,NLRMashapeClient 提供簡單和方便的形式來調用你在 Mashape 選擇的 APIs。
用法
以“ Ultimate Weather Forecasts”為例,這是一個免費的返回天氣狀況的API。登錄到Mashape并擁有至少一個應用程序后,將為Mashape Key每個應用程序獲得一個,以提出對此應用程序的請求。
首先,創(chuàng)建NLRMashapeClient的子類,并聲明單例方法,如下所示。
#import "NLRMashapeClient.h"
@interface WeatherClient : NLRMashapeClient
+ (instancetype)sharedClient;
@end
現(xiàn)在,應該使用正確的API名稱和Mashape App Key實現(xiàn)單例方法。API名稱是URL中位于之前的部分.p.mashape.com。例如,如果天氣API的基本網址為https://george-vustrey-weather.p.mashape.com,則應使用george-vustrey-weather??梢詮腗ashape的應用程序頁面中獲取應用程序密鑰,然后按“獲取密鑰”按鈕。
#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。
正確初始化客戶端后,就可以完成配置,并且可以進行任意數(shù)量的調用,而無需設置標題,鍵,而僅需注意:端點和參數(shù)!
例如,如果示例GET為https://george-vustrey-weather.p.mashape.com/api.php,而參數(shù)為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之前運行)。
評論
圖片
表情
