1.創建名為HTTPMethod(自己隨便起名字)的頭文件
2.導入AFNetworking頭文件(在github上下載最新版):
#import "AFNetworking.h"
3.在.h文件裡聲明類方法:
//參數解釋:(1)urlString是你想請求的網址 (2)bodyDic是POST請求時的參數 (3)dataBlock是數據請求成功後用來回調數據的block
+ (void)getDataByString:(NSString *)urlString BodyDic:(NSDictionary *)bodyDic WithDataBlock:(void(^)(id data))dataBlock;
4.方法的實現:
+(void)getDataByString:(NSString *)urlString BodyDic:(NSDictionary *)bodyDic WithDataBlock:(void (^)(id))dataBlock
{
//(1).字符串的轉碼
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlString]];
//(2).創建管理者對象(session)
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//(3).設置允許請求的類別
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", @"application/javascript", @"text/js", nil];
//(4).開始請求
if (!bodyDic) {
//如果bodyDic為空就執行get請求
[manager GET:urlString parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
dataBlock(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"請求失敗");
}];
}
else
{
[manager POST:urlString parameters:bodyDic success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
dataBlock(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"請求失敗");
}];
}
}