AFNetworking简单使用起来进行下载图片

继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"");
}];""

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值