AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of NSURLConnection, NSOperation, and other familiar Foundation technologies. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. For example, here's how easy it is to get JSON from a URL:
NSURL *url = [NSURL URLWithString:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"App.net Global Stream: %@", JSON);
} failure:nil];
[operation start];
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!
- Download AFNetworking and try out the included Mac and iPhone example apps
- Read the "Getting Started" guide, FAQ, or other articles in the wiki
- Check out the complete documentation for a comprehensive look at the APIs available in AFNetworking
- Watch the NSScreencast episode about AFNetworking for a quick introduction to how to use it in your application
- Questions? Stack Overflow is the best place to find answers
AFNetworking is architected to be as small and modular as possible, in order to make it simple to use and extend.
Core | |
---|---|
AFURLConnectionOperation | An NSOperation that implements the NSURLConnection delegate methods. |
HTTP Requests | |
AFHTTPRequestOperation | 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. |
AFJSONRequestOperation | A subclass of AFHTTPRequestOperation for downloading and working with JSON response data. |
AFXMLRequestOperation | A subclass of AFHTTPRequestOperation for downloading and working with XML response data. |
AFPropertyListRequestOperation | A subclass of AFHTTPRequestOperation for downloading and deserializing objects with property list response data. |
HTTP Client | |
AFHTTPClient |
Captures the common patterns of communicating with an web application over HTTP, including:
|
Images | |
AFImageRequestOperation | A subclass of AFHTTPRequestOperation for downloading and processing images. |
UIImageView+AFNetworking | Adds methods to UIImageView for loading remote images asynchronously from a URL. |
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.flickr.com/services/rest/?method=flickr.groups.browse&api_key=b6300e17ad3c506e706cb0072175d047&cat_id=34427469792%40N01&format=rest"]];
AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
XMLParser.delegate = self;
[XMLParser parse];
} failure:nil];
[operation start];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
// AFAppDotNetAPIClient is a subclass of AFHTTPClient, which defines the base URL and default HTTP headers for NSURLRequests it creates
[[AFAppDotNetAPIClient sharedClient] getPath:@"stream/0/posts/stream/global" parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
NSLog(@"App.net Global Stream: %@", JSON);
} failure:nil];
NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]];
operation.outputStream = [NSOutputStream outputStreamToMemory];
[operation start];
AFNetworking 1.0 and higher requires either iOS 5.0 and above, or Mac OS 10.7 (64-bit with modern Cocoa runtime) and above.
For compatibility with iOS 4.3, use the latest 0.10.x release.
AFNetworking uses ARC as of its 1.0 release.
If you are using AFNetworking 1.0 in your non-arc project, you will need to set a -fobjc-arc
compiler flag on all of the AFNetworking source files. Conversely, if you are adding a pre-1.0 version of AFNetworking, you will need to set a -fno-objc-arc
compiler flag.
To set a compiler flag in Xcode, go to your active target and select the "Build Phases" tab. Now select all AFNetworking source files, press Enter, insert -fobjc-arc
or -fno-objc-arc
and then "Done" to enable or disable ARC for AFNetworking.
AFNetworking includes a suite of unit tests within the Tests subdirectory. In order to run the unit tests, you must install the testing dependencies via CocoaPods. To do so:
$ gem install cocoapods # If necessary
$ cd Tests
$ pod install
Once CocoaPods has finished the installation, you can execute the test suite via the 'iOS Tests' and 'OS X Tests' schemes within Xcode.
By default, the unit tests do not emit any output during execution. For debugging purposes, it can be useful to enable logging of the requests and responses. Logging support is provided by the AFHTTPRequestOperationLogger extension, which is installed via CocoaPods into the test targets. To enable logging, edit the test Scheme and add an environment variable named AFTestsLoggingEnabled
with a value of YES
.
If you wish to execute the tests from the command line or within a continuous integration environment, you will need to install xctool. The recommended installation method is Homebrew.
To install the commandline testing support via Homebrew:
$ brew update
$ brew install xctool --HEAD
Once xctool is installed, you can execute the suite via rake test
.
AFNetworking was created by Scott Raymond and Mattt Thompson in the development of Gowalla for iPhone.
AFNetworking's logo was designed by Alan Defibaugh.
And most of all, thanks to AFNetworking's growing list of contributors.
Follow AFNetworking on Twitter (@AFNetworking)
AFNetworking is available under the MIT license. See the LICENSE file for more info.
@implementation PostTableViewCell { @private __strong Post *_post; }
@synthesize post = _post;
-
(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (!self) { return nil; }
self.textLabel.adjustsFontSizeToFitWidth = YES; self.textLabel.textColor = [UIColor darkGrayColor]; self.detailTextLabel.font = [UIFont systemFontOfSize:13.0f]; self.detailTextLabel.numberOfLines = 0;//等于0表示行数不确定可随内容变化 self.selectionStyle = UITableViewCellSelectionStyleGray;
return self; }
-
(void)setPost:(Post *)post { _post = post;
self.textLabel.text = _post.user.username; self.detailTextLabel.text = _post.text; [self.imageView setImageWithURL:_post.user.avatarImageURL placeholderImage:[UIImage imageNamed:@"profile-image-placeholder"]];
[self setNeedsLayout];//默认调用layoutSubviews }
//根据具体表单元的内容多少调整该行的高度 //字符串在指定区域内按照指定的字体显示时,需要的宽度和高度(而宽度在字符串只有一行时有用) //一般用法:指定区域的宽度而高度用MAXFLOAT,则返回值包含对应的高度 //如果指定区域的宽度指定,而字符串要显示的区域的高度超过了指定区域的高度,则高度返回0 //核心:多行显示,指定宽度,获取高度
-
(CGFloat)heightForCellWithPost:(Post *)post { CGSize sizeToFit = [post.text sizeWithFont:[UIFont systemFontOfSize:12.0f] constrainedToSize:CGSizeMake(220.0f, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
return fmaxf(70.0f, sizeToFit.height + 45.0f); }
//#pragma mark - UIView
//在自己定制的视图中重载这个方法,用来调整子视图的尺寸和位置。
-
(void)layoutSubviews { [super layoutSubviews];
self.imageView.frame = CGRectMake(10.0f, 10.0f, 50.0f, 50.0f); self.textLabel.frame = CGRectMake(70.0f, 10.0f, 240.0f, 20.0f);
CGRect detailTextLabelFrame = CGRectOffset(self.textLabel.frame, 0.0f, 25.0f); detailTextLabelFrame.size.height = [[self class] heightForCellWithPost:_post] - 45.0f; self.detailTextLabel.frame = detailTextLabelFrame; }
@end