基於AFNetworking3.0的網絡封裝


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(@"請求失敗");

        }];

    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM