您的位置:首页 > 移动开发 > IOS开发

ios 利用 NSURLSession下载图片

2016-07-25 16:24 549 查看
对于图片的下载

- (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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: