自定义一个下载类

1.新建一个cocoa类,取名Downloader,基类为NSObject。

自定义一个下载类_第1张图片


2.新建类代码

//
//  Downloader.h
//  OnlineMusic

#import <Foundation/Foundation.h>

// 定义一个BLOCK
typedef void(^DownloadBlock) (NSData *resultsData);

@interface Downloader : NSObject

// 单例操作:获取类的一个对象
+ (instancetype) sharedInstance;

// 提供下载的方法
-(void)downloadWithURL: (NSURL*)url complete: (DownloadBlock)block;


@end

//
//  Downloader.m
//  OnlineMusic
//
#import "Downloader.h"

@interface Downloader ()

@property (nonatomic, copy) DownloadBlock block;
@end

// 全局静态单例对象
static Downloader *instance = nil;

@implementation Downloader

+ (instancetype) sharedInstance {
    if (instance == nil)
    {
        instance = [[[self class] alloc] init];
    }
    return instance;
}

-(void) downloadWithURL:(NSURL *)url complete:(DownloadBlock)block{
    // 保存block
    self.block = block;
    
    dispatch_queue_t queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT);
    dispatch_async( queue, ^{
        // 执行下载任务
        // 创建一个request
        NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
        
        // 获取数据
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        
        // 将数据返回给调用者
        dispatch_sync(dispatch_get_main_queue(), ^{
            self.block(data);
        });
    });
}

@end


3.在主视图ViewController类的初始化函数中增加调度

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    // other codes                       
    
    // 下载数据.注意:如果提供的网址链接不正确,代码运行可能异常
    NSURL *url = [NSURL URLWithString:@"http://douban.fm/j/mine/playlist?channel=3"];
    [[Downloader sharedInstance] downloadWithURL:url complete:^(NSData* resultData) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultData options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@", dic);
    }];
}

4.执行后,输出:

2015-09-25 22:24:06.471 OnlineMusic[1432:55597] {
    "is_show_quick_start" = 0;
    r = 0;
    song =     (
                {
            aid = 1428537;
            album = "/subject/1428537/";
            albumtitle = "Greatest Hits, Vo...";
            "alert_msg" = "";
            artist = "Alan Jackson";
            "file_ext" = mp3;
            kbps = 128;
            length = 269;
            like = 0;
            picture = "http://img4.douban.com/lpic/s1442437.jpg";
            sha256 = 97ed83a589d4c952683b5f65ed347af8fd6543c11286e4b74eb0272888f23af6;
            sid = 277;
            singers =             (
                                {
                    id = 2900;
                    "is_site_artist" = 0;
                    name = "Alan Jackson";
                    "related_site_id" = 0;
                }
            );
            ssid = c231;
            status = 0;
            subtype = "";
            title = "Little Man";
            url = "http://mr7.doubanio.com/170a0467f3d8d87b2f21ace34986559d/0/fm/song/p277_128k.mp3";
            ver = 0;
        }
    );
}



你可能感兴趣的:(自定义一个下载类)