iOS開發-AFNetworking封裝Get和Post請求及檔案下載,ios-afnetworking
前面提到AFNetworking是一個很強大的網路三方庫,首先你需要引入AFNetworking三方庫;如封裝的有誤還請指出,謝謝!
1.Get請求
/**Get請求
url 伺服器請求地址
success 伺服器響應返回的結果
faile 失敗的資訊
*/
+ (void)getHttpRequestURL:(NSString *)url RequestSuccess:(void(^)(id repoes,NSURLSessionDataTask *task)) success RequestFaile:(void(^)(NSError *error))faile{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];//放棄解析
// NSArray *array = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:url]];
// NSDictionary *dict = [NSHTTPCookie requestHeaderFieldsWithCookies:array];
// NSLog(@"%@",dict);
[manager.requestSerializer setHTTPShouldHandleCookies:NO];
[manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
//返回成功結果
success(responseObject,task);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//返回失敗結果
faile(error);
}];
}
2.Post請求
/**Post請求
url 伺服器請求地址
pram 請求參數
success 伺服器響應返回的結果
faile 失敗的資訊
*/
+ (void)postHttpRequestURL:(NSString *)url RequestPram:(id)pram RequestSuccess:(void(^)(id respoes))success RequestFaile:(void(^)(NSError *erro))faile{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:url parameters:pram progress:^(NSProgress * _Nonnull uploadProgress) {
///這裡面是進度
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
//返回成功結果
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//返回失敗結果
faile(error);
}];
}
3.檔案下載
+ (void)createDownloadFileWithURLString:(NSString *)URLString downloadFileProgress:(void (^)(NSProgress *))downloadFileProgress setupFilePath:(NSURL *(^)(NSURLResponse *))setupFilePath downloadCompletionHandler:(void (^)(NSURL *, NSError *))downloadCompletionHandler{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURLSessionDownloadTask *dataTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
/**
* 下載進度
*/
downloadFileProgress(downloadProgress);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
/**
* 設定儲存目錄
*/
return setupFilePath(response);
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
/**
* 下載完成
*/
downloadCompletionHandler(filePath,error);
}];
[dataTask resume];
}
如有錯誤,還望指出!