iOS常用網路要求方法詳解

來源:互聯網
上載者:User

這個常用的網路要求方法優勢有:

1.get和post都可調用此方法
2.在UIViewController類裡直接用self指標即可調用(因為這個方法是寫在UIViewController分類裡的),在其他類只需用[UIViewController new]產生個指標即可進行網路請求
3.只需要傳入三個參數
4.代碼邏輯簡單易於理解
5.基於AFNetworking3.1.0

相關代碼:

建立一個繼承於AFHTTPSessionManager,名為AFAppDotNetAPIClient的類

 代碼如下 複製代碼

//AFAppDotNetAPIClient.h
 
#import <Foundation/Foundation.h>
#import <AFNetworking/AFNetworking.h>
@interface AFAppDotNetAPIClient : AFHTTPSessionManager
 
//建立單例類的方法聲明
+ (instancetype)sharedClient;
 
@end
 
//AFAppDotNetAPIClient.m
 
#import "AFAppDotNetAPIClient.h"
 
@implementation AFAppDotNetAPIClient
 
//建立單例類的方法實現
+ (instancetype)sharedClient{
    //初始化一個靜態類指標
    static AFAppDotNetAPIClient *sharedClient;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedClient = [AFAppDotNetAPIClient new];
        
        //AFNetworking要求標頭資訊相關設定
        sharedClient.requestSerializer = [AFJSONRequestSerializer serializer];
        [sharedClient.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        
        //AFNetworking擷取到的參數相關設定
        sharedClient.responseSerializer = [AFJSONResponseSerializer serializer];
        sharedClient.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/html", @"text/javascript", nil];
        //SSL相關設定
        sharedClient.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    });
    
    return sharedClient;
}
@end

寫在UIViewController分類裡的網路要求方法:

 代碼如下 複製代碼

- (NSURLSessionDataTask *)defaultRequestwithURL: (NSString *)URL withParameters: (NSDictionary *)parameters withMethod: (NSString *)method withBlock:(void (^)(NSDictionary *dict, NSError *error))block
{
    //預設列印傳入的實參
#ifdef DEBUG
    NSLog(@"common method = %@", method);//get 或 post
    NSLog(@"common URL = %@", URL);//所請求的網址
    NSLog(@"common parameters = %@", parameters);//傳入的參數
#endif
    
    //根據method字串判斷調用AFNetworking裡的get方法還是post方法
    if ( [method isEqualToString:@"GET"] ) {//所用到的是AFNetworking3.1.0裡的方法,其新加了progress進度block
        return [[AFAppDotNetAPIClient sharedClient] GET:URL parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
 
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable JSON) {
    #ifdef DEBUG
            NSLog(@"common get json = %@", JSON);//列印擷取到的json
    #endif
            
            NSDictionary *dict = JSON;//直接返回字典,方便使用
            
            if (block) {
                block(dict, nil);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //如果請求出錯返回空字典和NSError指標
            if (block) {
                block([NSDictionary dictionary], error);//這一點算是比較坑的地方了,因為比如我要根據一個欄位來判斷是否請求成功,我對一個空字典@{},
//根據一個key取value:[@{} objectForKey:@"errorCode"],
//然後判斷字串的intValue是否等於0:[[@{} objectForKey:@"errorCode"] intValue] == 0是返回1的。
//我想的解決辦法就是從伺服器端來改,返回的欄位key用isSuccess,value是字串True或False即可解決,
//但是這樣又只能知道成功或失敗並不能根據errorCode碼進行其他動作,因為errorCode可以為0、1、2、3等等。
            }
            
            //從指標級判斷error是否為空白,如果不為空白就列印error
            if (error) {
                NSLog(@"%@",error);
            }
        }];
    }
 
    //post相關代碼
    return [[AFAppDotNetAPIClient sharedClient]POST:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable JSON) {
    #ifdef DEBUG
        NSLog(@"common post json = %@", JSON);//列印擷取到的json
    #endif
        
        NSDictionary *dict = JSON;//直接返回字典,方便使用
        
        if (block) {
            block(dict, nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //如果請求出錯返回空字典和NSError指標
        if (block) {
            block([NSDictionary dictionary], error);
        }
        
        //從指標級判斷error是否為空白,如果不為空白就列印error
        if (error) {
            NSLog(@"%@",error);
        }
    }];
    
    //傳回值暫時用不到,不需要建立變數接收;傳進的self指標也沒有用到所以這個方法可移植性很強
}

-(void)request
{
    //測試網路要求方法
    //1.所用到的網址是本人以前抓到的,API是用php寫的,伺服器很穩定,我常用來測試,也僅供測試
    //2.get參數 start和end傳不帶正負號的整數
    NSDictionary *parameters = @{
                                 @"type":@"list",
                                 @"city":@"2",
                                 @"lid":@"31",
                                 @"sortby":@"1",
                                 @"start":@"0",
                                 @"end":@"3"
                                 };
  
    [self defaultRequestwithURL:@"/api.php" withParameters:parameters withMethod:@"GET" withBlock:^(NSDictionary *dict, NSError *error) {
 
    }];
}

額外附送多圖上傳方法,同樣基於AFNetworking3.1.0,和以上方法類似所以不加詳解注釋了:

 代碼如下 複製代碼

-(void)startMultiPartUploadTaskWithURL:(NSString *)url
                           imagesArray:(NSArray *)images
                     parameterOfimages:(NSString *)parameter
                        parametersDict:(NSDictionary *)parameters
                      compressionRatio:(float)ratio
                          succeedBlock:(void (^)(NSDictionary *dict))succeedBlock
                           failedBlock:(void (^)(NSError *error))failedBlock{
    if (images.count == 0) {
        NSLog(@"圖片數組計數為零");
        return;
    }
    for (int i = 0; i < images.count; i++) {
        if (![images[i] isKindOfClass:[UIImage class]]) {
            NSLog(@"images中第%d個元素不是UIImage對象",i+1);
        }
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        int i = 0;
        //根據當前系統時間產生圖片名稱
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy年MM月dd日"];
        NSString *dateString = [formatter stringFromDate:date];
        
        for (UIImage *image in images) {
            NSString *fileName = [NSString stringWithFormat:@"%@%d.png",dateString,i];
            NSData *imageData;
            if (ratio > 0.0f && ratio < 1.0f) {
                imageData = UIImageJPEGRepresentation(image, ratio);
            }else{
                imageData = UIImageJPEGRepresentation(image, 1.0f);
            }
            [formData appendPartWithFileData:imageData name:parameter fileName:fileName mimeType:@"image/jpg/png/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        NSLog(@"common post json = %@", dict);
        
        succeedBlock(dict);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            failedBlock(error);
            
            NSLog(@"%@",error);
        }
    }];
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.