继ASIHTTPRequest发布不再维护的消息之后,如果我们不使用CDN(云服务器),AFNetworking会是一套不错的选择 。
下載網址:https://github.com/AFNetworking/AFNetworking
下载之后,直接进入Xcode的工程即可以用,记得加入SystemConfiguration.framework
范例参考:
在application: didFinishLaunchingWithOptions: 加入AFNetworkActivityIndicatorManager
记得
#import "AFNetworkActivityIndicatorManager.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
这是我们常用的下载网路资源(JSON 格式)
记得
#import "AFHTTPClient.h"
#import "AFHTTPRequestOperation.h"
#import "JSONKit.h"
NSURL *url = [NSURL URLWithString:@"http://www.domain.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSString *_path=[NSString stringWithFormat:@"/user_login/%@/%@/",userName,password];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:_path parameters:nil];
[httpClient release];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//下载成功之后,使用JSONKit将字串转成NSDictionary或NSArray 格式
NSDictionary *deserializedData = [operation.responseString objectFromJSONString];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//下载失败的处理 }];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
我们做完上一个步骤,有時候会得到一些图片的绝对地址,接下來就是根据这些URL地址,进行异步下载图片。
记得 #import "UIImageView+AFNetworking.h"
简单的做法是
[imageView setImageWithURL:@"图片的绝对路径"];
复杂的做法,可以在图片下载完成之后,再去触发一些事件
NSURL *url = [NSURL URLWithString:@图片的绝对路径"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[imageView setImageWithURLRequest:request placeholderImage:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
NSLog(@"图片下载成功!do something");
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@图片下载成功!do something"");
}];""
转自:http://blog.csdn.net/nogodoss/article/details/8243316