AFNetworking 2.0

유명한 오픈 소스 네트워크 라 이브 러 리 AFNetworking 2.0 은 현재 Github 의 링크 글 만 번역 되 었 습 니 다.튜 토리 얼 을 사용 하려 면 클릭 하 십시오.
http://www.cnblogs.com/YouXianMing/p/3651462.html
 
https://github.com/AFNetworking/AFNetworking
 
AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of the Foundation URL Loading System, extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.
Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac.
Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did!
AFNetworking 이라는 네트워크 라 이브 러 리 를 사용 하여 개발 하면 기분 이 상쾌 해 질 것 이다.이 는 Foundation URL Loading System 의 상층 부 에 세 워 져 코코아 의 강력 한 네트워크 라 이브 러 리 를 고 차원 으로 확장 시 켰 다.그것 은 모듈 화 된 우수한 디자인 을 가지 고 있 으 며,각종 사용 하기 쉬 운 API 를 포함 하고 있 으 며,친 하지 않 아 도 낙오 된다.
가장 감동적인 것 은 이 인터넷 라 이브 러 리 가 못 하 는 것 이 없 는 것 이 아니다.매일 많은 개발 자 들 이 힘 을 합 쳐 이 네트워크 라 이브 러 리 를 업데이트 하고 이 네트워크 라 이브 러 리 에 자신의 힘 을 기여 합 니 다.
다음 프로젝트 에서 AFNetworking 을 선택 하 세 요.아니면 현재 프로젝트 에 이식 하 세 요.저 는 당신 이 많은 이익 을 얻 을 것 이 라 고 장담 합 니 다.
시작 하 는 방법(시작 하 는 방법)
Download AFNetworking and try out the included Mac and iPhone example apps
Read the "Getting Started" guide, FAQ, or other articles on the Wiki
Check out the documentation for a comprehensive look at all of the APIs available in AFNetworking
Questions? Stack Overflow is the best place to find answers
AFNetworking 의 소스 코드 를 다운로드 하고 Mac 과 iPhone 의 예를 시도 해 보 세 요.
입문 안내서,질문 및 답변,또는 위 키 의 관련 글 읽 기AFNetworking 이 제공 하 는 문서 자세히 보기문제 가 생 겼 어 요?Stack Overflow 에 올 라 가세 요2.0
AFNetworking 2.0 is a major update to the framework. Building on 2 years of development, this new version introduces powerful new features, while providing an easy upgrade path for existing users.
AFNetworking 2.0 은 매우 큰 업 데 이 트 를 가지 고 있 습 니 다.2 년 동안 이 라 이브 러 리 를 개발 하고 유지 하 는 토대 에서 새로운 버 전 은 더 많은 특성 을 가 져 왔 습 니 다.물론 그 는 AFNetworking 1.x 의 사용 자 를 버 리 지 않 고 1.x 에서 2.0 으로 업그레이드 하 는 간단 한 문 서 를 제공 합 니 다.
Read the AFNetworking 2.0 Migration Guide for an overview of the architectural and API changes.
What's New
Refactored Architecture
Support for NSURLSession
Serialization Modules
Expanded UIKit Extensions
Real-time functionality with Rocket
구 조 를 재 구성 했다NSURLSession 지원모듈 화 된 모델UIKit 확장??????
요구 사항(요구 사항)
AFNetworking 2.0 and higher requires Xcode 5, targeting either iOS 6.0 and above, or Mac OS 10.8 Mountain Lion (64-bit with modern Cocoa runtime) and above.
AFNetworking 2.0 및 후속 고 버 전 은 Xcode 5 에서 개발 해 야 하 며 iOS 버 전 은 6.0 이상,Mac OS 10.8 이상 이 필요 합 니 다.
For compatibility with iOS 5 or Mac OS X 10.7, use the latest 1.x release.
For compatibility with iOS 4.3 or Mac OS X 10.6, use the latest 0.10.x release.
iOS 5 나 Mac OS X 10.7 을 호 환 하기 위해 1.x 버 전 을 사용 합 니 다.
iOS 4.3 이나 Mac OS X 10.6 을 호 환 하기 위해 0.10.x 버 전 을 사용 합 니 다.
건축(구조)
NSURLConnection AFURLConnectionOperation AFHTTPRequestOperation AFHTTPRequestOperationManager
NSURLSession (iOS 7 / Mac OS X 10.9) AFURLSessionManager AFHTTPSessionManager
Serialization <AFURLRequestSerialization> AFHTTPRequestSerializer AFJSONRequestSerializer AFPropertyListRequestSerializer
<AFURLResponseSerialization> AFHTTPResponseSerializer AFJSONResponseSerializer AFXMLParserResponseSerializer AFXMLDocumentResponseSerializer  (Mac OS X) AFPropertyListResponseSerializer AFImageResponseSerializer AFCompoundResponseSerializer

Additional Functionality AFSecurityPolicy AFNetworkReachabilityManager
Usage(사용)
HTTP Request Operation Manager(HTTP 요청 조작 관리자)AFHTTPRequestOperationManager  encapsulates the common patterns of communicating with a web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as request operation management. AFHTTPRequestOperationManager  유 니 버 설 서버 응용 과 의 상호작용 을 패키지 합 니 다.요청 한 생 성,답장 의 직렬 화,네트워크 표시 기의 모니터링,안전성,물론 요청 작업 관리 도 포함 합 니 다.GET  요청(GET 요청)
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-Form-Encoded Request(폼 인 코딩 이 첨부 된 POST 요청)
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(복잡 한 POST 요청)
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);
}];

AFURLSessionManager AFURLSessionManager  creates and manages an  NSURLSession  object based on a specified  NSURLSessionConfiguration  object, which conforms to  <NSURLSessionTaskDelegate><NSURLSessionDataDelegate><NSURLSessionDownloadDelegate> , and  <NSURLSessionDelegate> . AFURLSessionManager  NSURLSession 을 관리 하 는 대상 을 만 들 었 습 니 다.지정 한NSURLSessionConfiguration대상 을 바탕 으로 다음 과 같은 프로 토 콜 과 융합 되 었 습 니 다<NSURLSessionTaskDelegate><NSURLSessionDataDelegate><NSURLSessionDownloadDelegate> , <NSURLSessionDelegate> )。
다운로드 작업 만 들 기(다운로드 작업 만 들 기)
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];

업로드 작업 만 들 기(업로드 작업 만 들 기)
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 Upload Task for a Multi-part 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];

데이터 작업 만 들 기(데이터 작업 만 들 기)
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 직렬 화(직렬 화 요청)
Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.
요청 직렬 화 기 는 URL 문자열 에서 요청,인 코딩 매개 변 수 를 만 들 고 문자열 이나 HTTPbody 부분 을 찾 습 니 다.
NSString *URLString = @"http://example.com";
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};

Query String Parameter Encoding(string 의 인 코딩 조회)
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3

URL Form Parameter Encoding(URL 폼 형식 매개 변수 인 코딩 조회)
[[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 Parameter Encoding(json 매개 변수 인 코딩 조회)
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
POST http://example.com/
Content-Type: application/json

{"foo": "bar", "baz": [1,2,3]}

네트워크 Reachability 관리자(모니터링 네트워크 관리자)AFNetworkReachabilityManager  monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. AFNetworkReachabilityManager  도 메 인 이름과 IP 주소 의 원활 성 을 모니터링 하여 WWAN 및 와 이 파이 의 네트워크 인터페이스 에 모두 사용 합 니 다.
Shared Network Reachability(단일 형식 으로 네트워크 의 유연성 을 검사)
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];

HTTP Manager with Base URL(기본 URL 로 HTTP 관리)
When a  baseURL  is provided, network reachability is scoped to the host of that base URL.
만약 에 기본 적 인 URL 주 소 를 제공 하면 그 기본 URL 사이트 의 유연성 은 자세하게 검 측 될 것 이다.
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;
    }
}];

Security Policy AFSecurityPolicy  evaluates server trust against pinned X.509 certificates and public keys over secure connections.
Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
Allowing Invalid SSL Certificates(불법 SSL 인증서 허용)
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production

AFHTTPRequestOperation AFHTTPRequestOperation  is a subclass of  AFURLConnectionOperation  for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
Although  AFHTTPRequestOperationManager  is usually the best way to go about making requests,  AFHTTPRequestOperation  can be used by itself. AFHTTPRequestOperation상속 자AFURLConnectionOperation, HTTP HTTPS 。 。 AFHTTPRequestOperationManager 현재 네트워크 요청 을 처리 하 는 가장 좋 은 방법 이지 만AFHTTPRequestOperation 그것 만 의 용도 도 있다.GET  with  AFHTTPRequestOperation( AFHTTPRequestOperation
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 Operations(많은 조작 이 함께 진행)
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];

좋은 웹페이지 즐겨찾기