1. 程式人生 > >iOS 【OC 封裝網路請求業務類(AFHTTPSessionManager)】

iOS 【OC 封裝網路請求業務類(AFHTTPSessionManager)】

由於AFNetworking底層請求由NSURLConnection更新為NSURLSession,管理者物件也由AFHTTPRequestOperationManager更新為AFURLSessionManager。

本文重點講述如何封裝AFN業務類,將第三方為程式帶來的汙染減小到最低。

讀者可以結合老版本AFHTTPRequestOperationManager的封裝去理解,具體請參考:

程式碼描述:

① 封裝業務類

//
//  WZYAFNTool.h
//  0716-02AFN上傳下載GETPOST-01
//
//  Created by 王中堯 on 16/7/16.
//  Copyright © 2016年 wzy. All rights reserved.
//

#import <Foundation/Foundation.h>
@class AFNetWorking;

@interface WZYAFNTool : NSObject

+ (void)get:(NSString *)url parameters:(id)params success:(void (^)(id object))success failure:(void (^)(NSError *error))failure;

+ (void)post:(NSString *)url parameters:(id)params success:(void (^)(id object))success failure:(void (^)(NSError *error))failure;

+ (void)unload:(NSString *)uploadUrl parameters:(id)params filePath:(NSString *)filePath name:(NSString *)name progress:(void (^)(NSProgress *))progress success:(void (^)(id object))success failure:(void (^)(NSError *))failure;

+ (void)download:(NSString *)url progress:(void (^)(NSProgress *progress))progress destination:(NSURL *(^)(NSURL *targetPath, NSURLResponse *response))destination failure:(void (^)(NSURLResponse * response, NSURL * filePath, NSError * error))failure;

@end

//
//  WZYAFNTool.m
//  0716-02AFN上傳下載GETPOST-01
//
//  Created by 王中堯 on 16/7/16.
//  Copyright © 2016年 wzy. All rights reserved.
//

#import "WZYAFNTool.h"
#import "AFNetworking.h"

@implementation WZYAFNTool

+ (void)get:(NSString *)url parameters:(id)params success:(void (^)(id object))success failure:(void (^)(NSError *error))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
        if (failure) {
            failure(error);
        }
        
    }];
}

+ (void)post:(NSString *)url parameters:(id)params success:(void (^)(id object))success failure:(void (^)(NSError *error))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failure) {
            failure(error);
        }
        
    }];
}

+ (void)unload:(NSString *)uploadUrl parameters:(id)params filePath:(NSString *)filePath name:(NSString *)name progress:(void (^)(NSProgress *progress))progress success:(void (^)(id object))success failure:(void (^)(NSError *error))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    [manager POST:uploadUrl parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        /*
         第一個引數:要上傳的檔案的URL
         第二個引數:後臺介面規定
         第三個引數:錯誤資訊
         */
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:filePath] name:name error:nil];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        if (progress) {
            progress(uploadProgress);
        }
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failure) {
            failure(error);
        }
        
    }];
}

+ (void)download:(NSString *)url progress:(void (^)(NSProgress *progress))progress destination:(NSURL *(^)(NSURL *targetPath, NSURLResponse *response))destination failure:(void (^)(NSURLResponse * response, NSURL * filePath, NSError * error))failure {
    // 1 建立會話管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 2 建立請求路徑 請求物件
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    // 3 建立請求下載操作物件
    NSURLSessionDownloadTask *downTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        if (progress) {
            progress(downloadProgress);
        }
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        if (destination) {
            return  destination(targetPath, response);
        } else {
            return nil;
        }
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (failure) {
            failure(response, filePath, error);
        }
    }];
    
    // 4 執行任務傳送下載操作請求
    [downTask resume];
}

@end

② 呼叫

//
//  ViewController.m
//  0716-02AFN上傳下載GETPOST-01
//
//  Created by 王中堯 on 16/7/16.
//  Copyright © 2016年 wzy. All rights reserved.
//

#import "ViewController.h"
#import "AFNetworking.h"

#import "WZYAFNTool.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 使用AFN原生方法
//    [self getAFN];
//    [self postAFN];
//    [self upload];
//    [self download];
    
    // 使用WZYAFNTool業務類
//    [self wzyGET];
//    [self wzyPOST];
//    [self wzyUpload];
//    [self wzyDownload];
}

// AFN GET請求
- (void)getAFN {
    
    // 1 封裝會話管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 2 拼接請求引數
    NSDictionary *dict = @{
                           @"username" : @"xxx",
                           @"pwd" : @"xxx",
                           @"type" : @"JSON"
                           };
    // 3 傳送請求
    /*
     第一個引數:請求路徑(!不包含引數) 型別是NSString
     以前:http://120.25.226.186:32812/login?username=xxx&pwd=xxx&type=JSON
     現在:http://120.25.226.186:32812/login
     第二個引數:引數(用字典來儲存引數)
     第三個引數:progress 進度回撥
     第四個引數:success成功之後的回撥
     responseObject:注意此引數是響應體(內部已經完成了反序列化處理:JSON--->OC,此處型別為id,也就是OC物件)
     task.response:響應頭
     第五個引數:failure 失敗之後的回撥
    */
    [manager GET:@"http://120.25.226.186:32812/login" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"success---%@---%@", responseObject, [responseObject class]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"failure---%@", error);
    }];
    
}
// WZYAFNTool GET請求
- (void)wzyGET {
    NSDictionary *dict = @{
                           @"username" : @"xxx",
                           @"pwd" : @"xxx",
                           @"type" : @"JSON"
                           };
    
    [WZYAFNTool get:@"http://120.25.226.186:32812/login" parameters:dict success:^(id object) {
        NSLog(@"success---%@", object);
    } failure:^(NSError *error) {
        NSLog(@"error---%@", error);
    }];
}


// AFN POST請求
- (void)postAFN {
    // 1 封裝會話管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 2 拼接請求引數
    NSDictionary *dict = @{
                           @"username" : @"xxx",
                           @"pwd" : @"xxx",
                           @"type" : @"JSON"
                           };
    // 3 傳送請求
    /*
     第一個引數:請求路徑(!不包含引數) 型別是NSString
     以前:http://120.25.226.186:32812/login?username=xxx&pwd=123&type=JSON
     現在:http://120.25.226.186:32812/login
     第二個引數:引數(用字典來儲存引數)
     第三個引數:progress 進度回撥
     第四個引數:success成功之後的回撥
     responseObject:注意此引數是響應體(內部已經完成了反序列化處理:JSON--->OC,此處型別為id,也就是OC物件)
     task.response:響應頭
     第五個引數:failure 失敗之後的回撥
     */
    [manager POST:@"http://120.25.226.186:32812/login" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"success---%@---%@", responseObject, [responseObject class]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"failure---%@", error);
    }];
}
// WZYAFNTool POST請求
- (void)wzyPOST {
    NSDictionary *dict = @{
                           @"username" : @"xxx",
                           @"pwd" : @"xxx",
                           @"type" : @"JSON"
                           };
    [WZYAFNTool post:@"http://120.25.226.186:33122/login" parameters:dict success:^(id object) {
        NSLog(@"success---%@", object);
    } failure:^(NSError *error) {
        NSLog(@"error---%@", error);
    }];
}


// AFN 上傳
- (void)upload {
    // 1 建立請求者物件
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 2 傳送POST請求上傳資料檔案
    NSDictionary *dict = @{@"wzy" : @"wangzhongyao"};
    
    /*
     第一個引數: 請求路徑
     第二個引數: 非檔案引數 (字典)
     第三個引數: constructingBodyWithBlock 處理上傳的檔案
     第四個引數: progress 進度回撥
     第五個引數: success 成功之後的回撥
     responseObject 響應體
     第六個引數: failure 失敗之後的回撥
     */
    
    [manager POST:@"http://120.25.226.186:31112/upload" parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        /*
         第一個引數:要上傳的檔案的URL
         第二個引數:後臺介面規定
         第三個引數:錯誤資訊
         */
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/wangzhongyao/Desktop/Snip20160716_17.png"] name:@"file" error:nil];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        // 上傳進度
        NSLog(@"unload --- %f", 1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //JSON--->OC 反序列化
        NSLog(@"響應體 --- %@",responseObject); // responseObject 響應體 在方法內部就反序列化成功
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 輸出錯誤資訊
        NSLog(@"%@", error);
    }];
}
// WZYAFNTool 上傳
- (void)wzyUpload {
    NSDictionary *dict = @{@"wzy" : @"wangzhongyao"};
    
    [WZYAFNTool unload:@"http://120.25.226.186:32812/upload" parameters:dict filePath:@"/Users/wangzhongyao/Desktop/Snip20160716_17.png" name:@"file" progress:^(NSProgress *progress) {
        
        // 上傳進度
        NSLog(@"unload --- %f", 1.0 *progress.completedUnitCount / progress.totalUnitCount);
    } success:^(id object) {
        
        //JSON--->OC 反序列化
        NSLog(@"響應體 --- %@",object); // responseObject 響應體 在方法內部就反序列化成功
    } failure:^(NSError *error) {
        
        // 輸出錯誤資訊
        NSLog(@"%@", error);
    }];
    
}


// AFN 下載
- (void)download {
    
    /*
     第一個引數: 請求物件
     第二個引數: progress進度回撥
     第三個引數: destination URL處理的回撥
               targetPath:檔案下載到沙盒中的臨時路徑
               response:響應頭資訊
     返回值: 告訴AFN檔案應該剪下到什麼地方
     第四個引數: completionHandler完成之後的回撥
               filePath:就是檔案的最終儲存位置
     */
    
    // 1 建立會話管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 2 建立請求路徑 請求物件
    NSURL *url = [NSURL URLWithString:@"http://www.bz55.com/uploads/allimg/150326/140-150326141213-50.jpg"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
   
    // 3 建立請求下載操作物件
    NSURLSessionDownloadTask *downTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        // 計算進度
        NSLog(@"downloading --- %f", 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        // 獲得檔案下載儲存的全路徑
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        NSLog(@"fullPath --- %@, tmpPath --- %@", fullPath, targetPath); // 列印需要修改的全路徑 & 臨時路徑
        
        // 該方法會拼接上協議頭 file:// 成為一個完整的URL,而URLWithString不會自動拼接協議頭
        return [NSURL fileURLWithPath:fullPath]; // 該block是有返回值的,返回檔案剪下儲存的路徑
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"filePath --- %@", filePath);
    }];
    
    // 4 執行任務傳送下載操作請求
    [downTask resume];
}
// WZYAFNTool 下載
- (void)wzyDownload {
    [WZYAFNTool download:@"http://www.bz55.com/uploads/allimg/150326/140-150326141213-50.jpg" progress:^(NSProgress *progress) {
        
        // 計算進度
        NSLog(@"downloading --- %f", 1.0 * progress.completedUnitCount / progress.totalUnitCount);
        
    } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        // 獲得檔案下載儲存的全路徑
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        NSLog(@"fullPath --- %@, tmpPath --- %@", fullPath, targetPath); // 列印需要修改的全路徑 & 臨時路徑
        
        // 該方法會拼接上協議頭 file:// 成為一個完整的URL,而URLWithString不會自動拼接協議頭
        return [NSURL fileURLWithPath:fullPath];
        
    } failure:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        
        NSLog(@"filePath --- %@", filePath); // filePath --- (null)
        
    }];
}

@end


相關推薦

iOS OC 封裝網路請求業務AFHTTPSessionManager

由於AFNetworking底層請求由NSURLConnection更新為NSURLSession,管理者物件也由AFHTTPRequestOperationManager更新為AFURLSessionManager。 本文重點講述如何封裝AFN業務類,將第三方為程式帶來的

iOS network-封裝業務AFNetworkingAFHTTPSessionManager

http://www.2cto.com/kf/201607/527908.html 由於AFNetworking底層請求由NSURLConnection更新為NSURLSession,管理者物件也由AFHTTPRequestOperationManager更新為

簡單封裝網路請求工具

package com.mjd.imitate_jd.utils; import com.mjd.imitate_jd.api.GetInterface; import java.util.concurrent.TimeUnit; import okhttp3.OkHt

Android 原生HttpURLConnection網路請求工具get post)

public class NetworkUtil { /* * 傳入一個Url地址 返回一個JSON字串 * 網路請求的情況分析: * 如果是404 500 .

Selenium2selenium之 定位以及切換frameiframe

js xml imp int webdriver 寫法 pre avr ray -a 參考:http://blog.csdn.net/huilan_same/article/details/52200586 總有人看不明白,以防萬一,先在開頭大寫加粗說明一下: fra

題解 P1801 黑匣子_NOI導刊2010提高06

amp 平衡樹 clu 實現 cto ctype 一位 mark 排序 我看正解已經有一大堆了,我就發個不太正經的吧 最近不會高級數據結構的蒟蒻在搞STL,搞完普通平衡樹後就看到了這道題,本來想用黑科技pb_ds中的紅黑樹做的,發現已經有大佬貼了一篇。set的做法也有人發

2018百度之星初賽A1002 度度熊學隊列

std php begin include push_back targe ref 使用 sin 題目地址:http://acm.hdu.edu.cn/showproblem.php?pid=6375 Knowledge Point:   STL - map:ht

MapReduce詳解及原始碼解析——分片輸入、Mapper及Map端Shuffle過程

title: 【MapReduce詳解及原始碼解析(一)】——分片輸入、Mapper及Map端Shuffle過程 date: 2018-12-03 21:12:42 tags: Hadoop categories: 大資料 toc: true 點選檢視我的部落格:Josonlee’

手把手教你樹莓派3 裝機

概述 raspberry pi其實可以看做一個微型的計算機,我們可以在上面裝各種作業系統,然後搭建伺服器,當然這只是它的一小點功能罷了。。。與我們常用的PC機不同的是,ras pi有GPIO,我們可以讓raspberry pi來控制這些引腳,從而傳送一些物理訊號給其他的裝置

Redis詳解基礎篇二命令

這裡寫自定義目錄標題前言操作 前言 操作 寫鍵值對 set key value 獲取鍵值對 get key 切換資料庫 select 15 //預設是有16個數據庫 直接到指定的

Redis詳解基礎篇三持久化

前言 什麼是持久化 因為redis是存放在記憶體中的,所以我們的資料很可能會丟失。所以得讓他持久化的保留起來就肯定需要硬碟,也就是放到裝置上進行儲存 使用場景 如果你想用redis暫時性的存放一些資料,只是存放之後設定一個超時的時間,那麼你可以不需要redi

Unity 3D 5.6版本使用3點選物體彈出視窗顯示狀態

emmm直接看程式碼 using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShowWindow : MonoBehavio

Java開發手冊之異常日誌異常處理

【強制】不要捕獲 Java 類庫中定義的繼承自 RuntimeException 的執行時異常類,如: IndexOutOfBoundsException / NullPointerException,這類異常由程式設計師預檢查 來規避,保

Java開發手冊之異常日誌日誌規約

【強制】應用中不可直接使用日誌系統 (Log 4 j 、 Logback) 中的 API ,而應依賴使用日誌框架SLF 4 J 中的 API ,使用門面模式的日誌框架,有利於維護和各個類的日誌處理方式統一。 import org.slf4j.Logg

iOS開發總結之block回撥以AFN為基礎封裝網路請求操作

1.#warning封裝網路請求類的好處 /**  *  1.專案存在問題,太依賴第三方框架。     2.為什麼要封裝網路請求:以後AFN升級,方法名改了,或者AFN淘汰了,直接改工具類就

iOS重構-輕量級的網路請求封裝實踐

前言 在十分鐘搭建主流框架_簡單的網路部分(OC) 中,我們使用AFN框架順利的傳送網路請求並返回了有用資料,但對AFN框架的依賴十分嚴重,下面我們重構一下。 原始碼github地址 初步 很多時候,我們涉及到網路請求這塊,都離不開幾個第三方框架,AFNetw

網路請求工具和mvp的封裝

1.okhttp工具 public class OkHttpUtil { private static final String METHOD_GET = "GET"; private static OkHttpClient client; private sta

iOS開發:NSUrlSession網路請求封裝

網路請求AFNetworking使用量不用過多的說了,但是在開發過程中,需要用到自己去封裝一個網路請求,此處主要是說一下NSUrlSession的用法; 首先建立一個繼承與NSObject的.h和.m的類,.h中的程式碼如下: #import &

iOS AFN監聽網路封裝網路請求 —— HERO部落格

對AFN網路請求進行封裝,程式碼如下:/************************* .h檔案 *************************/ #import <Foundation/Foundation.h> @interface HWManage

微信小程式封裝網路請求並在wxml呼叫

正文: // url:網路請求的url method:網路請求方式 data:請求引數 message:提示資訊 success:成功的回撥函式 fail:失敗的回撥 //pages/utils/