ios 利用 NSURLSession下载图片

对于图片的下载

- (void)loadImageFromNet
{
    [[TFNetWorkManager sharedInstances] requestNetWork:requestUrl successBlock:^(NSData *netData)
    {
        //在主线程中刷新界面
        dispatch_async(dispatch_get_main_queue(), ^{
            _imageView.image = [[UIImage alloc]initWithData:netData];
            [_imageView setNeedsLayout];
        });
    } failure:^(NSError *error){
        
        CHDebugLog(@"-----failure---%@",error);
    }];
}

封装的下载图片的源码如下

#import <Foundation/Foundation.h>

typedef void(^successBlock)(NSData *netData);

typedef void (^failBlock)(NSError *error);


@interface TFNetWorkManager : NSObject

@property (nonatomic,copy) successBlock successBlock;
@property (nonatomic,copy) failBlock failBlock;

+ (TFNetWorkManager*)sharedInstances;

//网络请求
- (void)requestNetWork:(NSString*)urlStr
          successBlock:(successBlock)success
               failure:(failBlock)failure;

@end


#import "TFNetWorkManager.h"

@interface TFNetWorkManager ()<NSURLSessionDataDelegate,NSURLSessionDelegate,NSURLSessionTaskDelegate>

@property (nonatomic, strong) NSMutableData *mutableData;

@end

@implementation TFNetWorkManager

+ (TFNetWorkManager*)sharedInstances
{
    static dispatch_once_t once;
    static TFNetWorkManager *_netWorkManager;
    dispatch_once(&once,^{
        _netWorkManager = [[TFNetWorkManager alloc]init];
    });
    
    return _netWorkManager;
}

- (instancetype)init
{
    self = [super init];
    if (!self)
    {
        return nil;
    }
    
    self.mutableData = [NSMutableData data];
 
    return self;
}


- (void)requestNetWork:(NSString*)urlStr
          successBlock:(successBlock)success
               failure:(failBlock)failure
{
    self.successBlock = success;
    self.failBlock = failure;
    
    //测试通过
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
    [task resume];
}

#pragma mark NSURLSessionDataDelegate

// 1.接收到服务器的响应
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    // 允许处理服务器的响应,才会继续接收服务器返回的数据
    completionHandler(NSURLSessionResponseAllow);
}

// 2.接收到服务器的数据(可能调用多次)

/* Sent when data is available for the delegate to consume.  It is
 * assumed that the delegate will retain and not copy the data.  As
 * the data may be discontiguous, you should use
 * [NSData enumerateByteRangesUsingBlock:] to access it.
 */
- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data
{
    // 处理每次接收的数据
    [self.mutableData appendData:data];
}

// 3.请求成功或者失败(如果失败,error有值)
- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
    NSData *data = nil;
    if (self.mutableData)
    {
        data = [self.mutableData copy];
        self.mutableData = nil;
    }

    // 请求完成,成功或者失败的处理
    if (data)
    {
        if (self.successBlock !=nil)
        {
            self.successBlock(data);
        }
    }

    if (error)
    {
        if (self.failBlock != nil)
        {
            self.failBlock(error);
        }
    }
}

#pragma mark NSURLSessionTaskDelegate

/* Notification that a data task has become a download task.  No
 * future messages will be sent to the data task.
 */
- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
{

}

/*
 * Notification that a data task has become a bidirectional stream
 * task.  No future messages will be sent to the data task.  The newly
 * created streamTask will carry the original request and response as
 * properties.
 *
 * For requests that were pipelined, the stream object will only allow
 * reading, and the object will immediately issue a
 * -URLSession:writeClosedForStream:.  Pipelining can be disabled for
 * all requests in a session, or by the NSURLRequest
 * HTTPShouldUsePipelining property.
 *
 * The underlying connection is no longer considered part of the HTTP
 * connection cache and won't count against the total number of
 * connections per host.
 */
- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
didBecomeStreamTask:(NSURLSessionStreamTask *)streamTask
{

}
@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值