AFNetworking是一個爲 iOS 和 Mac OSX 製做的使人愉快的網絡庫

  • AFNetworking是一個爲 iOS 和 Mac OSX 製做的使人愉快的網絡庫,它創建在URL 裝載系統框架的頂層,內置在Cocoa裏,擴展了強有力的高級網絡抽象。它的模塊架構被良好的設計,擁有豐富的功能,所以,使用起來,一定賞心悅目。

    @介紹
      1.支持HTTP請求和基於REST的網絡服務(包括GET、POST、 PUT、DELETE等)html

  •   2.支持ARCios

  •   3.要求iOS 5.0及以上版本web

  •   4.UIKit擴展
    @配置
    1.下載AFNetworking,將2個文件夾:AFNetworking和UIKit+AFNetworking拖入工程
    2.導入如下庫文件:CFNetwork、Security、SystemConfiguration、MobileCoreServices
    3.若是你之前用的是1.0版本,那麼AFNetworking 2.0 Migration Guide能幫助你
    4.若是你是用CocoaPods配置的,那麼
    platform:ios,'7.0'
    pod"AFNetworking","~>2.0"
    @使用
    1.HTTP請求操做
    AFHTTPRequestOperationManager封裝的共同模式與web應用程序經過HTTP通訊,包括建立請求,響應序列化,網絡可達性監控、運營管理和安全,以及請求。
    *GET請求
     
    view source
    print
    ?


    1.
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];


    2.
    [manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {


    3.
    NSLog(@"JSON: %@", responseObject);


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


    5.
    NSLog(@"Error: %@", error);


    6.
    }];




     
    *POST請求
     
    view source
    print
    ?


    1.
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];


    2.
    NSDictionary *parameters = @{@"foo": @"bar"};


    3.
    [manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {


    4.
    NSLog(@"JSON: %@", responseObject);


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


    6.
    NSLog(@"Error: %@", error);


    7.
    }];




    *POST請求(多表)  
     
    view source
    print
    ?


    01.
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];


    02.
    NSDictionary *parameters = @{@"foo": @"bar"};


    03.
    NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];


    04.
    [manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {


    05.
    [formData appendPartWithFileURL:filePath name:@"image" error:nil];


    06.
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {


    07.
    NSLog(@"Success: %@", responseObject);


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


    09.
    NSLog(@"Error: %@", error);


    10.
    }];




     
    2.AFURLSessionManager(NSURLSession詳細見網絡編程(6))
    建立和管理制定的NSURLSession對象NSURLSessionConfiguration對象必須實現<NSURLSessionTaskDelegate>, <NSURLSessionDataDelegate>, <NSURLSessionDownloadDelegate>, <NSURLSessionDelegate>協議
    *建立一個下載任務
     
    view source
    print
    ?


    01.
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];


    02.
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];


    03.
     


    04.
    NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];


    05.
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];


    06.
     


    07.
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {


    08.
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];


    09.
    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];


    10.
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {


    11.
    NSLog(@"File downloaded to: %@", filePath);


    12.
    }];


    13.
    [downloadTask resume];




    *建立一個上傳任務  
     
    view source
    print
    ?


    01.
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];


    02.
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];


    03.
     


    04.
    NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];


    05.
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];


    06.
     


    07.
    NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];


    08.
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {


    09.
    if (error) {


    10.
    NSLog(@"Error: %@", error);


    11.
    } else {


    12.
    NSLog(@"Success: %@ %@", response, responseObject);


    13.
    }


    14.
    }];


    15.
    [uploadTask resume];




    *建立一個帶多表,進度的上傳任務  
     
    view source
    print
    ?


    01.
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {


    02.
    [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];


    03.
    } error:nil];


    04.
     


    05.
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];


    06.
    NSProgress *progress = nil;


    07.
     


    08.
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {


    09.
    if (error) {


    10.
    NSLog(@"Error: %@", error);


    11.
    } else {


    12.
    NSLog(@"%@ %@", response, responseObject);


    13.
    }


    14.
    }];


    15.
     


    16.
    [uploadTask resume];




    *建立一個數據流Data任務  
     
    view source
    print
    ?


    01.
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];


    02.
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];


    03.
     


    04.
    NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];


    05.
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];


    06.
     


    07.
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {


    08.
    if (error) {


    09.
    NSLog(@"Error: %@", error);


    10.
    } else {


    11.
    NSLog(@"%@ %@", response, responseObject);


    12.
    }


    13.
    }];


    14.
    [dataTask resume];




     
    3.網絡監測(通常會用另外一個網絡監測類,Reachability,還有JSON解析方法,反正我也通常不用,自行腦補)
    AFNetworkReachabilityManager監控網絡領域的可達性,WWAN地址和WiFi接口.
    *當前網絡狀態
     
    view source
    print
    ?


    1.
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {


    2.
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));


    3.
    }];




    編程

  • *HTTP Manager 可達性  
     
    view source
    print
    ?


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


    02.
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];


    03.
     


    04.
    NSOperationQueue *operationQueue = manager.operationQueue;


    05.
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {


    06.
    switch (status) {


    07.
    case AFNetworkReachabilityStatusReachableViaWWAN:


    08.
    case AFNetworkReachabilityStatusReachableViaWiFi:


    09.
    [operationQueue setSuspended:NO];


    10.
    break;


    11.
    case AFNetworkReachabilityStatusNotReachable:


    12.
    default:


    13.
    [operationQueue setSuspended:YES];


    14.
    break;


    15.
    }


    16.
    }];




     
    4.AFHTTPRequestOperation
    AFHTTPRequestOperation是使用HTTP或HTTPS協議的AFURLConnectionOperation的子類。
    它封裝的獲取後的HTTP狀態和類型將決定請求的成功與否。雖然AFHTTPRequestOperationManager一般是最好的去請求的方式,可是AFHTTPRequestOpersion也可以單獨使用。
    *GET請求
     
    view source
    print
    ?


    01.
    NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"];


    02.
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];


    03.
    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];


    04.
    op.responseSerializer = [AFJSONResponseSerializer serializer];


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


    06.
    NSLog(@"JSON: %@", responseObject);


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


    08.
    NSLog(@"Error: %@", error);


    09.
    }];


    10.
    [[NSOperationQueue mainQueue] addOperation:op];




    json

  • *批量多請求  
     
    view source
    print
    ?


    01.
    NSMutableArray *mutableOperations = [NSMutableArray array];


    02.
    for (NSURL *fileURL in filesToUpload) {


    03.
    NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {


    04.
    [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];


    05.
    }];


    06.
     


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


    08.
     


    09.
    [mutableOperations addObject:operation];


    10.
    }


    11.
     


    12.
    NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {


    13.
    NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);


    14.
    } completionBlock:^(NSArray *operations) {


    15.
    NSLog(@"All operations in batch complete");


    16.
    }];


    17.
    [[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];




    安全

  • @其餘資料  網絡

延伸閱讀:架構

相關文章
相關標籤/搜索