網(wǎng)絡(luò)請求POST和GET的封裝

import <Foundation/Foundation.h>

一 聲明屬性和方法

// 請求數(shù)據(jù)成功之后進(jìn)行回調(diào) 返回NSData

typedef void(^Finish)(NSData *data);

// 請求數(shù)據(jù)失敗之后進(jìn)行回調(diào) 返回NSError

typedef void(^Error)(NSError *error);

// 請求方式的枚舉

typedef NS_ENUM(NSInteger,RequestType){

RequestGET,

RequestPOST

};

@interface RequestManager : NSObject

@property (nonatomic,copy)Finish finish;

@property (nonatomic,copy)Error error;

  • (void)requestWithUrlString:(NSString *)urlString requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error;

import "RequestManager.h"

@implementation RequestManager

  • (void)requestWithUrlString:(NSString *)urlString requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error{
RequestManager *request = [[RequestManager alloc]init];


[request requestWithUrlString:urlString requestType:requestType parDic:parDic finish:finish error:error];

}

  • (void)requestWithUrlString:(NSString *)urlString requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error{

    // 對block屬性進(jìn)行賦值

    self.finish = finish;

    self.error = error;

    NSURL *url = [NSURL URLWithString:urlString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    request.timeoutInterval = 10;

    // 如果是POST請求

    if (requestType == RequestPOST) {
    [request setHTTPMethod:@"POST"];

      if (parDic.count > 0) {
          [request setHTTPBody:[self parDicToPOSTData:parDic]];
      }
    

    }

NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    if (error) {
        self.error(error);
    }
    
    else{
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.finish(data);
        });
    }
}];

//  調(diào)用此方法才是異步鏈接

[task resume];

}

  • (NSData *)parDicToPOSTData:(NSDictionary *)parDic{
NSMutableArray *array = [NSMutableArray array];

for (NSString *key in parDic) {
    NSString *string = [NSString stringWithFormat:@"%@=%@",key,parDic[key]];
    
    [array addObject:string];
}

NSString *postString = [array componentsJoinedByString:@"&"];

return [postString dataUsingEncoding:NSUTF8StringEncoding];

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容