Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
This repository was archived by the owner on Jan 17, 2023. It is now read-only.

A delightful networking framework for iOS, macOS, watchOS, and tvOS.

License

NotificationsYou must be signed in to change notification settings

AFNetworking/AFNetworking

Repository files navigation

As of Jan. 17, 2023, AFNetworking is deprecated and there will be no further releases. This repo will remain online in perpetuity as an archive. There are a couple options for continued AFNetworking use:

  1. Copy AFNetworking into your project and compile it directly. This gives you full control over the code.
  2. Fork AFNetworking and use the fork in your dependency manager. There will be no official forks but anyone can fork at any time and can even publish those forks under a different name, in accordance with AFNetworking's license.

Moving forward, Alamofire is the suggested migration path for networking in modern Swift. Anyone who needs help making that migration is welcome to ask onStackOverflow and tagalamofire andafnetworking, or open a discussion on Alamofire'sGitHub Discussions regarding any migration issues or missing features.


AFNetworking

Build StatusCocoaPods CompatibleCarthage CompatiblePlatformTwitter

AFNetworking is a delightful networking library for iOS, macOS, watchOS, and tvOS. It's built on top of theFoundation 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.

How To Get Started

Communication

  • If youneed help, useStack Overflow. (Tag 'afnetworking')
  • If you'd like toask a general question, useStack Overflow.
  • If youfound a bug,and can provide steps to reliably reproduce it, open an issue.
  • If youhave a feature request, open an issue.
  • If youwant to contribute, submit a pull request.

Installation

AFNetworking supports multiple methods for installing the library in a project.

Installation with CocoaPods

To integrate AFNetworking into your Xcode project using CocoaPods, specify it in yourPodfile:

pod'AFNetworking','~> 4.0'

Installation with Swift Package Manager

Once you have your Swift package set up, adding AFNetworking as a dependency is as easy as adding it to thedependencies value of yourPackage.swift.

dependencies:[.package(url:"https://github.com/AFNetworking/AFNetworking.git",.upToNextMajor(from:"4.0.0"))]

Note: AFNetworking's Swift package does not include it's UIKit extensions.

Installation with Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate AFNetworking, add the following to yourCartfile.

github "AFNetworking/AFNetworking" ~> 4.0

Requirements

AFNetworking VersionMinimum iOS TargetMinimum macOS TargetMinimum watchOS TargetMinimum tvOS TargetNotes
4.xiOS 9macOS 10.10watchOS 2.0tvOS 9.0Xcode 11+ is required.
3.xiOS 7OS X 10.9watchOS 2.0tvOS 9.0Xcode 7+ is required.NSURLConnectionOperation support has been removed.
2.6 -> 2.6.3iOS 7OS X 10.9watchOS 2.0n/aXcode 7+ is required.
2.0 -> 2.5.4iOS 6OS X 10.8n/an/aXcode 5+ is required.NSURLSession subspec requires iOS 7 or OS X 10.9.
1.xiOS 5Mac OS X 10.7n/an/a
0.10.xiOS 4Mac OS X 10.6n/an/a

(macOS projects must support64-bit with modern Cocoa runtime).

Programming in Swift? TryAlamofire for a more conventional set of APIs.

Architecture

NSURLSession

  • AFURLSessionManager
  • AFHTTPSessionManager

Serialization

  • <AFURLRequestSerialization>
    • AFHTTPRequestSerializer
    • AFJSONRequestSerializer
    • AFPropertyListRequestSerializer
  • <AFURLResponseSerialization>
    • AFHTTPResponseSerializer
    • AFJSONResponseSerializer
    • AFXMLParserResponseSerializer
    • AFXMLDocumentResponseSerializer(macOS)
    • AFPropertyListResponseSerializer
    • AFImageResponseSerializer
    • AFCompoundResponseSerializer

Additional Functionality

  • AFSecurityPolicy
  • AFNetworkReachabilityManager

Usage

AFURLSessionManager

AFURLSessionManager creates and manages anNSURLSession object based on a specifiedNSURLSessionConfiguration object, which conforms to<NSURLSessionTaskDelegate>,<NSURLSessionDataDelegate>,<NSURLSessionDownloadDelegate>, and<NSURLSessionDelegate>.

Creating a Download Task

NSURLSessionConfiguration *configuration = [NSURLSessionConfigurationdefaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManageralloc]initWithSessionConfiguration:configuration];NSURL *URL = [NSURLURLWithString:@"http://example.com/download.zip"];NSURLRequest *request = [NSURLRequestrequestWithURL:URL];NSURLSessionDownloadTask *downloadTask = [managerdownloadTaskWithRequest:requestprogress:nildestination:^NSURL *(NSURL *targetPath,NSURLResponse *response) {NSURL *documentsDirectoryURL = [[NSFileManagerdefaultManager]URLForDirectory:NSDocumentDirectoryinDomain:NSUserDomainMaskappropriateForURL:nilcreate:NOerror:nil];return [documentsDirectoryURLURLByAppendingPathComponent:[responsesuggestedFilename]];}completionHandler:^(NSURLResponse *response,NSURL *filePath,NSError *error) {NSLog(@"File downloaded to:%@", filePath);}];[downloadTaskresume];

Creating an Upload Task

NSURLSessionConfiguration *configuration = [NSURLSessionConfigurationdefaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManageralloc]initWithSessionConfiguration:configuration];NSURL *URL = [NSURLURLWithString:@"http://example.com/upload"];NSURLRequest *request = [NSURLRequestrequestWithURL:URL];NSURL *filePath = [NSURLfileURLWithPath:@"file://path/to/image.png"];NSURLSessionUploadTask *uploadTask = [manageruploadTaskWithRequest:requestfromFile:filePathprogress:nilcompletionHandler:^(NSURLResponse *response,id responseObject,NSError *error) {if (error) {NSLog(@"Error:%@", error);    }else {NSLog(@"Success:%@%@", response, responseObject);    }}];[uploadTaskresume];

Creating an Upload Task for a Multi-Part Request, with Progress

NSMutableURLRequest *request = [[AFHTTPRequestSerializerserializer]multipartFormRequestWithMethod:@"POST"URLString:@"http://example.com/upload"parameters:nilconstructingBodyWithBlock:^(id<AFMultipartFormData> formData) {        [formDataappendPartWithFileURL:[NSURLfileURLWithPath:@"file://path/to/image.jpg"]name:@"file"fileName:@"filename.jpg"mimeType:@"image/jpeg"error:nil];    }error:nil];AFURLSessionManager *manager = [[AFURLSessionManageralloc]initWithSessionConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]];NSURLSessionUploadTask *uploadTask;uploadTask = [manageruploadTaskWithStreamedRequest:requestprogress:^(NSProgress * _Nonnull uploadProgress) {// This is not called back on the main queue.// You are responsible for dispatching to the main queue for UI updatesdispatch_async(dispatch_get_main_queue(), ^{//Update the progress view                      [progressViewsetProgress:uploadProgress.fractionCompleted];                  });              }completionHandler:^(NSURLResponse * _Nonnull response,id  _Nullable responseObject,NSError * _Nullable error) {if (error) {NSLog(@"Error:%@", error);                  }else {NSLog(@"%@%@", response, responseObject);                  }              }];[uploadTaskresume];

Creating a Data Task

NSURLSessionConfiguration *configuration = [NSURLSessionConfigurationdefaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManageralloc]initWithSessionConfiguration:configuration];NSURL *URL = [NSURLURLWithString:@"http://httpbin.org/get"];NSURLRequest *request = [NSURLRequestrequestWithURL:URL];NSURLSessionDataTask *dataTask = [managerdataTaskWithRequest:requestcompletionHandler:^(NSURLResponse *response,id responseObject,NSError *error) {if (error) {NSLog(@"Error:%@", error);    }else {NSLog(@"%@%@", response, responseObject);    }}];[dataTaskresume];

Request Serialization

Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.

NSString *URLString =@"http://example.com";NSDictionary *parameters = @{@"foo":@"bar",@"baz": @[@1, @2, @3]};

Query String Parameter Encoding

[[AFHTTPRequestSerializerserializer]requestWithMethod:@"GET"URLString:URLStringparameters:parameterserror:nil];
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3

URL Form Parameter Encoding

[[AFHTTPRequestSerializerserializer]requestWithMethod:@"POST"URLString:URLStringparameters:parameterserror:nil];
POST http://example.com/Content-Type: application/x-www-form-urlencodedfoo=bar&baz[]=1&baz[]=2&baz[]=3

JSON Parameter Encoding

[[AFJSONRequestSerializerserializer]requestWithMethod:@"POST"URLString:URLStringparameters:parameterserror:nil];
POST http://example.com/Content-Type: application/json{"foo": "bar", "baz": [1,2,3]}

Network Reachability Manager

AFNetworkReachabilityManager monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.

  • Do not use Reachability to determine if the original request should be sent.
    • You should try to send it.
  • You can use Reachability to determine when a request should be automatically retried.
    • Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something.
  • Network reachability is a useful tool for determining why a request might have failed.
    • After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out."

See alsoWWDC 2012 session 706, "Networking Best Practices.".

Shared Network Reachability

[[AFNetworkReachabilityManagersharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {NSLog(@"Reachability:%@",AFStringFromNetworkReachabilityStatus(status));}];[[AFNetworkReachabilityManagersharedManager]startMonitoring];

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

AFHTTPSessionManager *manager = [AFHTTPSessionManagermanager];manager.securityPolicy.allowInvalidCertificates =YES;// not recommended for production

Unit Tests

AFNetworking includes a suite of unit tests within the Tests subdirectory. These tests can be run simply be executed the test action on the platform framework you would like to test.

Credits

AFNetworking is owned and maintained by theAlamofire Software Foundation.

AFNetworking was originally created byScott Raymond andMattt Thompson in the development ofGowalla for iPhone.

AFNetworking's logo was designed byAlan Defibaugh.

And most of all, thanks to AFNetworking'sgrowing list of contributors.

Security Disclosure

If you believe you have identified a security vulnerability with AFNetworking, you should report it as soon as possible via email tosecurity@alamofire.org. Please do not post it to a public issue tracker.

License

AFNetworking is released under the MIT license. SeeLICENSE for details.


[8]ページ先頭

©2009-2025 Movatter.jp