AFNetWorking源碼詳解(二)

來源:互聯網
上載者:User

標籤:

 

來源:Yuzeyang 

連結:http://zeeyang.com/2016/03/15/AFNetWorking-two/

 

AFHTTPSessionManager繼承於AFURLSessionManager,提供了更方便的HTTP要求方法,包括了GET、POST、PUT、PATCH、DELETE這五種方式,並且AF鼓勵我們在AFHTTPSessionManager再進行一次封裝來滿足我們自己的業務需求

 

 

在開始的地方,AF一直提醒到一個屬性baseURL,這個變數你可以在進一步封裝的時候,將baseURL寫成你自己的HTTP請求原始地址,比如

 

+ (NSURL *)baseURL {

    return [NSURL URLWithString:kBaseURLString];

}

 

在對baseURL進行拼接的時候,也需要注意一下幾點,防止出現請求的URL出現問題

 

NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];

    [NSURL URLWithString:@"foo" relativeToURL:baseURL];                  // http://example.com/v1/foo

    [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL];          // http://example.com/v1/foo?bar=baz

    [NSURL URLWithString:@"/foo" relativeToURL:baseURL];                 // http://example.com/foo

    [NSURL URLWithString:@"foo/" relativeToURL:baseURL];                 // http://example.com/v1/foo

    [NSURL URLWithString:@"/foo/" relativeToURL:baseURL];                // http://example.com/foo/

    [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/

 

在初始化的方法裡面,我們看到這個方法

 

- (instancetype)initWithBaseURL:(nullable NSURL *)url;

- (instancetype)initWithBaseURL:(nullable NSURL *)url

           sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;

 

NS_DESIGNATED_INITIALIZER的作用是什麼呢?

 

指定的構造器通過發送初始化訊息到父類來保證object被完全初始化,指定構造器有以下幾個規則:

 

1.指定構造器必須調用父類的指定構造器

 

2.任何一個便利構造器必須調用最終指向指定構造器的其他構造器

 

3.具有指定構造器的類必須實現父類的所有指定構造器

 

- (instancetype)init {

    // 指向- [initWithBaseURL:]

  return [self initWithBaseURL:nil];

}

 

- (instancetype)initWithBaseURL:(NSURL *)url {

    // 指向- [initWithBaseURL:sessionConfiguration:]

    return [self initWithBaseURL:url sessionConfiguration:nil];

}

 

- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {

    // 指向- [initWithBaseURL:sessionConfiguration:]

    return [self initWithBaseURL:nil sessionConfiguration:configuration];

}

 

- (instancetype)initWithBaseURL:(NSURL *)url

           sessionConfiguration:(NSURLSessionConfiguration *)configuration

{

    // 調用父類的- [initWithSessionConfiguration:]

    self = [super initWithSessionConfiguration:configuration];

    if (!self) {

        return nil;

    }

 

    // baseURL賦值,AFHTTPRequestSerializer和AFJSONResponseSerializer序列化

    

    return self;

}

 

DEPRECATED_ATTRIBUTE這個相信大家見得比較多了,字面意思就是這個API不建議開發人員再使用了,再使用時,會出現編譯警告

 

- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString

                   parameters:(nullable id)parameters

                      success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success

                      failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE;

 

 

下面POST、GET、PUT、PATCH、DELETE方法傳參基本都是大同小異

 

URLString表示請求的URL,parameters表示用戶端請求內容的儲存空間,progress表示請求的進度,constructingBodyWithBlock裡面只有一個formData用來拼接到HTTP的請求體,success表示請求成功後的block回調,failure表示請求失敗的block回調

 

那麼這幾個請求有什麼區別呢?

 

1、POST請求是向服務端發送資料的,用來更新資源資訊,它可以改變資料的種類等資源

 

2、GET請求是向服務端發起請求資料,用來擷取或查詢資源資訊

 

3、PUT請求和POST請求很像,都是發送資料的,但是PUT請求不能改變資料的種類等資源,它只能修改內容

 

4、DELETE請求就是用來刪除某個資源的

 

5、PATCH請求和PUT請求一樣,也是用來進行資料更新的,它是HTTP verb推薦用於更新的

 

在實際開發過程中,我們還是使用POST和GET請求是最多的

 

 

在請求實現的部分,都是調用了-[dataTaskWithHTTPMethod:URLString:parameters:uploadProgress:downloadProgress:success:failure]方法建立NSURLSessionDataTask對象

 

傳參的內容基本都是和上一層方法一樣,method指的就是請求的類型

 

- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method

                                       URLString:(NSString *)URLString

                                      parameters:(id)parameters

                                  uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress

                                downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress

                                         success:(void (^)(NSURLSessionDataTask *, id))success

                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure

{

 

    NSError *serializationError = nil;

    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];

    if (serializationError) {

        if (failure) {

#pragma clang diagnostic push

#pragma clang diagnostic ignored "-Wgnu"

            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{

                failure(nil, serializationError);

            });

#pragma clang diagnostic pop

        }

 

        return nil;

    }

 

    __block NSURLSessionDataTask *dataTask = nil;

    dataTask = [self dataTaskWithRequest:request

                          uploadProgress:uploadProgress

                        downloadProgress:downloadProgress

                       completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {

        // 失敗成功處理

    }];

 

    return dataTask;

}

 

AFNetWorking源碼詳解(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.