IOS cainiao's AFN secondary encapsulation and iosafn secondary Encapsulation

Source: Internet
Author: User

IOS cainiao's AFN secondary encapsulation and iosafn secondary Encapsulation

I used a singleton class to encapsulate some common network requests, including the resumable upload and download functions of the get request for post requests for uploading and downloading image files.

First, download AFN from github, drag the AFNetworking folder in the folder into the project, and then create an image file parameter class Code as follows:

# Import <Foundation/Foundation. h> @ interface UploadParam: NSObject/*** uploads binary data of a file */@ property (nonatomic, strong) NSData * data; /*** name of the uploaded parameter */@ property (nonatomic, copy) NSString * name;/*** name of the file uploaded to the server */@ property (nonatomic, copy) NSString * fileName;/*** upload file type */@ property (nonatomic, copy) NSString * mimeType; @ end
#import "UploadParam.h"@implementation UploadParam@end

The specific code for creating the network tool AFNManager is as follows (here I provide two methods for you to pass values through proxy and block ):

# Import <Foundation/Foundation. h> # import "AFNManagerDelegate. h "# import" UploadParam. h "@ interface AFNManager: NSObject @ property (nonatomic, weak) id <AFNManagerDelegate> delegate;/*** AFNManager */+ (AFNManager *) sharedManager; # pragma mark -- pass the value as a proxy/*** get */-(void) GET :( NSString *) URLString parameters :( id) parameters; /*** post */-(void) Post :( NSString *) URLString parameters :( id) parameters;/*** upload */-(void) Upload :( NSString *) URLString parameters :( id) parameters uploadParam :( UploadParam *) uploadParam; # pragma mark-pass the value in the form of block/*** get request */-(void) GET :( NSString *) URLString parameters :( id) parameters succeed :( void (^) (id data) succeed failure :( void (^) (NSError * error) failure; /*** post Request */-(void) Post :( NSString *) URLString parameters :( id) parameters succeed :( void (^) (id data )) succeed failure :( void (^) (NSError * error) failure;/*** upload */-(void) Upload :( NSString *) URLString parameters :( id) parameters uploadParam :( UploadParam *) uploadParam succeed :( void (^) (id data) succeed failure :( void (^) (NSError * error) failure; # pragma mark -- resumable download/*** start to download resumable download ** @ param URLString request interface */-(void) downloadStartWithUrl :( NSString *) URLString fileName :( NSString *) fileName;/*** start to upload resumable upload ** @ param URLString request interface */-(void) uploadStartWithUrl :( NSString *) URLString fileData :( NSData *) fileData; /*** pause the resumable upload operation */-(void) operationPause;/*** resume the resumable upload operation */-(void) operationResume; /*** cancel Operation */-(void) operationCancel; @ end
# Import "AFNManager. h "# import" AFNetworking. h "@ interface AFNManager () {AFHTTPRequestOperation * operation; // CREATE request management (for upload and download)} @ endstatic AFNManager * manager = nil; @ implementation AFNManager + (AFNManager *) sharedManager {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {if (manager = nil) {manager = [[self alloc] init] ;}}); return manager ;} + (instancetype) allocWithZone :( struct _ NSZone *) Zone {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {if (manager = nil) {manager = [super allocWithZone: zone] ;}}); return manager ;} -(void) GET :( NSString *) URLString parameters :( id) parameters {// CREATE request manager AFHTTPRequestOperationManager * mgr = [AFHTTPRequestOperationManager manager]; [mgr GET: URLString parameters: parameters success: ^ (AFHTTPRequestOperation * operation, id responseO Bject) {if (self. delegate & [self. delegate respondsToSelector: @ selector (AFNManagerDidSuccess :)]) {[self. delegate AFNManagerDidSuccess: responseObject] ;}} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {if (self. delegate & [self. delegate respondsToSelector: @ selector (AFNManagerDidFaild :)]) {[self. delegate AFNManagerDidFaild: error] ;}}] ;}- (void) Post :( NSString *) URLString parame Ters :( id) parameters {// CREATE request manager AFHTTPRequestOperationManager * mgr = [AFHTTPRequestOperationManager]; [mgr POST: URLString parameters: parameters success: ^ (AFHTTPRequestOperation * operation, id responseObject) {if (self. delegate & [self. delegate respondsToSelector: @ selector (AFNManagerDidSuccess :)]) {[self. delegate AFNManagerDidSuccess: responseObject] ;}} failure: ^ (AFHTTPRequestOperation * Operation, NSError * error) {if (self. delegate & [self. delegate respondsToSelector: @ selector (AFNManagerDidFaild :)]) {[self. delegate AFNManagerDidFaild: error] ;}}] ;}- (void) Upload :( NSString *) URLString parameters :( id) parameters uploadParam :( UploadParam *) uploadParam {// create a request manager AFHTTPRequestOperationManager * mgr = [AFHTTPRequestOperationManager manager]; [mgr POST: URLString parameters: parameter S constructingBodyWithBlock: ^ (id <AFMultipartFormData> formData) {// concatenate all uploaded files to formData/*** FileData: binary data of the file to be uploaded * name: upload parameter name * fileName: name of the file uploaded to the server * mimeType: file type */[formData appendPartWithFileData: uploadParam. data name: uploadParam. name fileName: uploadParam. fileName mimeType: uploadParam. mimeType];} success: ^ (AFHTTPRequestOperation * operation, id responseObject) {if (self. delegate & [self. Delegate respondsToSelector: @ selector (AFNManagerDidSuccess :)]) {[self. delegate AFNManagerDidSuccess: responseObject] ;}} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {if (self. delegate & [self. delegate respondsToSelector: @ selector (AFNManagerDidFaild :)]) {[self. delegate AFNManagerDidFaild: error] ;}}] ;}- (void) GET :( NSString *) URLString parameters :( id) parameters succeed :( void (^) (Id) succeed failure :( void (^) (NSError *) failure {// create a request manager AFHTTPRequestOperationManager * mgr = [AFHTTPRequestOperationManager manager]; [mgr GET: URLString parameters: parameters success: ^ (AFHTTPRequestOperation * operation, id responseObject) {if (responseObject = nil) {return;} succeed (responseObject);} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {failure (error) ;}] ;}- (Void) Post :( NSString *) URLString parameters :( id) parameters succeed :( void (^) (id) succeed failure :( void (^) (NSError *)) failure {// CREATE request manager AFHTTPRequestOperationManager * mgr = [AFHTTPRequestOperationManager]; [mgr POST: URLString parameters: parameters success: ^ (AFHTTPRequestOperation * operation, id responseObject) {if (responseObject = nil) {return;} succeed (responseObject);} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {failure (error);}];}-(void) Upload :( NSString *) URLString parameters :( id) parameters uploadParam :( UploadParam *) uploadParam succeed :( void (^) (id) succeed failure :( void (^) (NSError *) failure {// CREATE request manager AFHTTPRequestOperationManager * mgr = [AFHTTPRequestOperationManager]; [mgr POST: URLString parameters: parameters constructingBodyWithBlock: ^ (Id <AFMultipartFormData> formData) {// concatenate all uploaded files to formData/*** FileData: binary data of the file to be uploaded * name: Upload parameter name * fileName: name of the file uploaded to the server * mimeType: file type */[formData appendPartWithFileData: uploadParam. data name: uploadParam. name fileName: uploadParam. fileName mimeType: uploadParam. mimeType];} success: ^ (AFHTTPRequestOperation * operation, id responseObject) {if (self. delegate & [self. delegate respondsToSelector: @ Selector (AFNManagerDidSuccess :)]) {succeed (responseObject) ;}} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {if (self. delegate & [self. delegate respondsToSelector: @ selector (AFNManagerDidFaild :)]) {failure (error) ;}] ;}- (void) downloadStartWithUrl :( NSString *) URLString fileName :( NSString *) fileName {NSString * filePath = [NSString stringWithFormat: @ "% @/Documents/% @", NSHomeDire Ctory (), fileName]; operation = [[AFHTTPRequestOperation alloc] initWithRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: URLString]; operation. outputStream = [NSOutputStream outputStreamToFileAtPath: filePath append: NO]; // you can set the progress bar here // [operation setDownloadProgressBlock: ^ (NSUInteger bytesRead, long totalBytesRead, long timeout) {//}]; _ weak typeof (self) w Eakself = self; [operation setCompletionBlockWithSuccess: ^ (AFHTTPRequestOperation * operation, id responseObject) {// prompt if (weakself. delegate & [weakself. delegate respondsToSelector: @ selector (AFNManagerDidSuccess :)]) {[weakself. delegate AFNManagerDidSuccess: responseObject] ;}} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {// if (weakself. delegate & [weakself.de Legate respondsToSelector: @ selector (AFNManagerDidFaild :)]) {[weakself. delegate AFNManagerDidFaild: error] ;}}]; [operation start] ;}- (void) uploadStartWithUrl :( NSString *) URLString fileData :( NSData *) fileData {operation = [[AFHTTPRequestOperation alloc] initWithRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: URLString]; operation. inputStream = [[NSInputStream alloc] initWithData: fileDa Ta]; // set the progress bar // [operation setUploadProgressBlock: ^ (NSUInteger bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite) {//}]; _ weak typeof (self) weakself = self; [operation setCompletionBlockWithSuccess: ^ (AFHTTPRequestOperation * operation, id responseObject) {// if (weakself. delegate & [weakself. delegate respondsToSelector: @ selector (AFNManagerDidSuccess :)]) {[Weakself. delegate AFNManagerDidSuccess: responseObject] ;}} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {// if (weakself. delegate & [weakself. delegate respondsToSelector: @ selector (AFNManagerDidFaild :)]) {[weakself. delegate AFNManagerDidFaild: error];}]; [operation start];}-(void) operationPause {[operation pause];}-(void) operationResume {[operation resume];} -(vo Id) operationCancel {[operation cancel];} // network listener (used to check whether the network can be connected. This method is recommended in AppDelegate to enable the program to detect the network.)-(void) reachabilityManager {AFHTTPRequestOperationManager * mgr = [AFHTTPRequestOperationManager manager]; // enable the network listener [mgr. reachabilityManager startMonitoring]; // listens for network changes [mgr. reachabilityManager setReachabilityStatusChangeBlock: ^ (AFNetworkReachabilityStatus status) {switch (status) {// when the network is unavailable (no network or request delay) case AFNetworkReachabilityStatusNotReachable: break; // case AFNetworkReachabilityStatusReachableViaWiFi: break when mobile phone WiFi is used; // case AFNetworkReachabilityStatusReachableViaWWAN: break when mobile phone cellular data network is used; // other cases default: break;}]; //// stop the network listener (if you need to continuously check the network status, you can keep it running without stopping) // [mgr. reachabilityManager stopMonitoring];} @ end

The network tool proxy protocol code is as follows:

# Import <Foundation/Foundation. h> @ class AFNManager; @ protocol AFNManagerDelegate <NSObject> @ optional/*** request sent successfully ** @ param manager AFNManager */-(void) AFNManagerDidSuccess :( id) data; /*** failed to send the request ** @ param manager AFNManager */-(void) AFNManagerDidFaild :( NSError *) error; @ end

If you have many shortcomings, please comment on them or pay attention to them for technical exchanges. In the future, I will also write some of my daily learning experiences.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.