AFNetworking的二次封裝

來源:互聯網
上載者:User

標籤:http   io   ar   os   sp   for   strong   on   資料   

//

//  NetworkService.m

//  AFNetworking - demo

//

//  Created by liman on 14-12-2.

//  Copyright (c) 2014年 liman. All rights reserved.

//

 

#import "NetworkService.h"

 

@implementation NetworkService

 

#pragma mark - public methods

// GCD單例

+ (NetworkService *)sharedService;

{

    static NetworkService *__singletion;

    

    static dispatch_once_t onceToken;

    

    dispatch_once(&onceToken, ^{

        

        __singletion = [[self alloc] init];

        

    });

    

    return __singletion;

}

 

 

// 請求網路資料

- (void)requestDataWithFrontURL:(NSString *)frontURL method:(NSString *)method parameter:(NSDictionary *)parameter header:(NSDictionary *)header body:(NSString *)body timeoutInterval:(NSTimeInterval)timeoutInterval result:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

{

    // 開啟狀態列菊花

    [self open];

    

    // GET方法單獨特殊處理 =================================================================================

    

    if ([method isEqualToString:@"GET"])

    {

        // 1.初始化

        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

        

        

        // 2.佈建要求格式 (預設二進位, 這裡不用改也OK)

        manager.requestSerializer = [AFHTTPRequestSerializer serializer];

        

        

        // 3.設定逾時時間

        manager.requestSerializer.timeoutInterval = timeoutInterval;

        

        

        // 4.設定訊息頭

        if (header) {

            

            for (NSString *key in [header allKeys]) {

                [manager.requestSerializer setValue:[header objectForKey:key] forHTTPHeaderField:key];

            }

        }

        

        

        // 5.設定返回格式 (預設JSON, 這裡必須改為二進位)

        manager.responseSerializer = [AFHTTPResponseSerializer serializer];

        

        

        // 6.請求

        [manager GET:frontURL parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {

            

            // 成功

            success(operation, responseObject);

            

            // 關閉狀態列菊花

            [self close];

            

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            

            // 逾時

            failure(operation, error);

            

            // 關閉狀態列菊花

            [self close];

        }];

    }

    

    

    

    

    // POST, PUT方法通用處理 =================================================================================

    

    if ([method isEqualToString:@"POST"] || [method isEqualToString:@"PUT"])

    {

        // 0. 拼接完整的URL地址

        NSMutableArray *laterArr = [NSMutableArray array];

        

        for (NSString *key in [parameter allKeys]) {

            

            NSString *keyValue = [key stringByAppendingFormat:@"=%@",[parameter objectForKey:key]];

            [laterArr addObject:keyValue];

        }

        

        NSString *laterURL = [laterArr componentsJoinedByString:@"&"];

        NSString *finalURL = [frontURL stringByAppendingFormat:@"?%@", laterURL];

        

        

        // 1.初始化

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:finalURL]];

        

        

        // 2.佈建要求類型

        request.HTTPMethod = method;

        

        

        // 3.設定逾時時間

        request.timeoutInterval = timeoutInterval;

        

        

        // 4.設定訊息頭

        if (header) {

            

            for (NSString *key in [header allKeys]) {

                [request setValue:[header objectForKey:key] forHTTPHeaderField:key];

            }

        }

        

        

        // 5.設定訊息體

        if (body) {

            

            request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];

        }

        

        

        // 6.請求

        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

        

        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

            

            // 成功

            success(operation, responseObject);

            

            // 關閉狀態列菊花

            [self close];

            

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            

            // 逾時

            failure(operation, error);

            

            // 關閉狀態列菊花

            [self close];

        }];

        

        [operation start];

    }

}

 

#pragma mark - private methods

// 開啟狀態列菊花

- (void)open

{

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

}

 

// 關閉狀態列菊花

- (void)close

{

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

}

 

@end

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.