iosネットワークプログラミングのAFNetWorking


AFNetWorkingの最新バージョンはすでに2.4.1になりました.ダウンロードアドレス:http://afnetworking.com/
AFNetWorkingはiOS and Mac OS X用の良いネットワークライブラリです.システムのURLに基づいてライブラリをロードしてコンパイルされました.Cocoaの上に、より強力なネットワーク抽象を広げます.それは綿密に設計されたモジュール化システム構造を持っていて、機能が豊富なAPIを提供しています.
最も重要な特徴は、しかし、驚くべきコミュニティの開発者は毎日AFNetworkingを使って、AFNetworkingに貢献しています.iPhone、iPad、Macでは、多くの優れたアプリケーションがAFNetworkingを使っています.
あなたの次のプロジェクトのためにAFNetworkingを選択したり、既存のプロジェクトに移行したりしたら、あなたはあなたのために心を高めます.
How To Get Startd(どうやって開始しますか?)
  • Download AFNetworking and try out the includ Mac and iPhone example apps
  • Read the 「Getting Startd」ガイド、 FAQ、or other articles on the Wiki
  • Check out the documentation for a compprehensive look at all of the API s available in AFNetworking
  • Read the AFNetworking 2.0 Migrationガイド for an overview of the architectural changes from 1.0.
  • Communication(交流)
  • If you need help,use Stock Overflow.(Tag'afnetworking')
  • If you'd like to ask a general question、use Stock Overflow.
  • If you found a bug,open an issue.
  • If you have a feature request,open an issue.
  • If you want to contribute、submit a pull request.
  • Installation with CocoaPods(CocoaPodsでインストール)
    CocoaPods is a dependency manager for Objective-C,which atomast and simplifies the process of using 3 rd-party libries like Atworking in your projects.See the 「Getting Startd」ガイドfor more information.
    PODFILE
    platform :ios, '7.0'
    pod "AFNetworking", "~> 2.0"
    
    Requirements(必須条件)
    AFNetworking Verssion
    Minimm iOS Target
    Minimum OS X Target
    ノーツ
    2.x
    iOS 6
    OS X 10.8
    Xcode 5 is required.  AFHTTPSessionManager requires iOS 7 or OS X 10.9.
    1.x
    iOS 5
    Mac OS X 10.7
     
    0.10.x
    iOS 4
    Mac OS X 10.6
     
    (OS Xプロジェクトスmust support 64ビットwith moden Cocoa runtime)
    Architecture(構造)
    NSURLConnection
  • AFURLConnectionOperation
  • AFHTTPRequestOperation
  • AFHTTPRequestOperationManager
  • NSURLSession (iOS 7/Mac OS X 10.9)
  • AFURLSessionManager
  • AFHTTPSessionManager
  • Serialization
  • AFHTTPRequestSerializer
  • AFJSONRequestSerializer
  • AFPropertyListRequestSerializer
  • AFHTTPResponseSerializer
  • AFJSONResponseSerializer
  • AFXMLParserResponseSerializer
  • AFXMLDocumentResponseSerializer (Mac OS X)
  • AFPropertyListResponseSerializer
  • AFImageResponseSerializer
  • AFCompoundResponseSerializer
  • Additional Functionality
  • AFSecurityPolicy
  • AFNetworkReachabilityManager
  • Usage
    HTTP Request Operation ManagerAFHTTPRequestOperationManager encapulates the common patterns of communication with a web appplication over HTTP,including request creation,reponse serialization,network reachability monight,and security,as well werequest operation manation.GET REQUST
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    
    POST URL-FOM-ENCODED REQUEst
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"foo": @"bar"};
    [manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    
    POST MULTI-Part REQUEST
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"foo": @"bar"};
    NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
    [manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:filePath name:@"image" error:nil];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    
    AFRURLSessionManagerAFURLSessionManager creates and managers an  NSURLSession object based on a specified NSURLSessionConfiguration object、which conforms to 、  、and  .
    CREATING A DOWNLOAD TASK
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"File downloaded to: %@", filePath);
    }];
    [downloadTask resume];
    
    CREATING AN UPLOAD TASK
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            NSLog(@"Success: %@ %@", response, responseObject);
        }
    }];
    [uploadTask resume];
    
    CREATING AN UPSAD TASK FOR A MUSLTI-PIART REQUEST,WITH PROGRESS
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
        } error:nil];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;
    
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            NSLog(@"%@ %@", response, responseObject);
        }
    }];
    
    [uploadTask resume];
    
    CREATING A DATATATATATASK
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            NSLog(@"%@ %@", response, responseObject);
        }
    }];
    [dataTask resume];
    
    Request Serialzation
    Request serializers create requests from URL stings,encoding parameters as eigher a query string or HTTP body.
    NSString *URLString = @"http://example.com";
    NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
    
    QUERY STRING PARDER ENCODING
    [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
    
    GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
    
    URL FORM PARDER ENCODING
    [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
    
    POST http://example.com/
    Content-Type: application/x-www-form-urlencoded
    
    foo=bar&baz[]=1&baz[]=2&baz[]=3
    
    JSON PAAMETER ENCODING
    [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
    
    POST http://example.com/
    Content-Type: application/json
    
    {"foo": "bar", "baz": [1,2,3]}
    
    Network Reachability ManagerAFNetworkReachabilityManager monitors the reachability of domans,and address for both WWAN and WiFi network interfaces.
    SHARED NETWORK REACHABILITY
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
    }];
    
    HTTP MANAGER REACHABILITY
    NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"];
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
    
    NSOperationQueue *operationQueue = manager.operationQueue;
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [operationQueue setSuspended:NO];
                break;
            case AFNetworkReachabilityStatusNotReachable:
            default:
                [operationQueue setSuspended:YES];
                break;
        }
    }];
    
    [manager.reachabilityManager startMonitoring];
    
    Security PolicyAFSecurityPolicy evaluates server trust against pinned X.509 certificates and public keys over secure connections.
    Adding pinned SSL certificates to your ap helps prevent man-the-middle atch and other vulneration.Application s dealing with sensitive customer data or financial information are stronight stongly encouredtonication.
    ALLOWING INVALLID SSL CERTIFFICATES
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production
    
    AHTTPRequest OperationAFHTTPRequestOperation is a subclass of  AFURLConnectionOperation for requests using the HTTP or HTTPS protocols.It encapulates the concept of accept able status codes and content types,which determine the success or failure of a request.
    Although  AFHTTPRequestOperationManager is usualy the best way to go about making requests、  AFHTTPRequestOperation can be used by itself.GET WITH  AFHTTPREQUESTOPERATION(get )
    NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    op.responseSerializer = [AFJSONResponseSerializer serializer];
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    [[NSOperationQueue mainQueue] addOperation:op];
    
    BATCH OF OPARTATIONS(バッチ操作)
    NSMutableArray *mutableOperations = [NSMutableArray array];
    for (NSURL *fileURL in filesToUpload) {
        NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];
        }];
    
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    
        [mutableOperations addObject:operation];
    }
    
    NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
        NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);
    } completionBlock:^(NSArray *operations) {
        NSLog(@"All operations in batch complete");
    }];
    [[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];
    
    ユニットTests(ユニットテスト)
    AFNetworking includes a suit tests within the Tests subdirectory.In order to run the unit tests,you must install the testing dependencies via CocoaPods:
    $ cd Tests
    $ pod install
    
    Onese testing dependencies are installed,you can execute the test suite via the'iOS Tests'and'OS X Tests'schemes within Xcode.
    Running Tests from the Command Line(コマンドライン運転テスト)
    Tests can also be run from the command line or within a continuous integration environment.The xcpretty utility needs to be installed before running the tests from the command line:
    $ gem install xcpretty
    
    Once  xcpretty is installed,you can execute the suite via  rake test.
    Crediits(スタッフ)
    AFNetworking was originally created by Scrott Raymond and Mattt Thompson in the development oGowalla for iPhone.
    AFNetworking's logo was designed by Alan Defibagh.
    And most of all,thanks to AFNetwork's growing list of contributors.
    Contact(連絡)
    Follow AFNetworking on Twitter(@AFNetworking)
    Maintainers
  • Mattt Thompson (@matt)
  • License
    AFNetworking is available under the MIT license.See the LICENSE file for more info.