#import "DownLoadMp3.h"
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
static DownLoadMp3 *sharedObj = nil;
NSMutableArray *arrList;
@implementation DownLoadMp3
+ (DownLoadMp3 *) sharedInstance
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
arrList=[[NSMutableArray alloc] init];
sharedObj=[[DownLoadMp3 alloc] init];
});
return sharedObj;
}
+ (id) allocWithZone:(NSZone *)zone //第三步:重写allocWithZone方法
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedObj=[super allocWithZone:zone];
});
return sharedObj;
}
- (id) copyWithZone:(NSZone *)zone //第四步
{
return self;
}
-(void)downLoadUrl:(NSString *)fileUrl{
if (fileUrl==nil||[fileUrl length]==0) {
return;
}
if (!([fileUrl hasPrefix:@"http://"]||[fileUrl hasPrefix:@"https://"])) {
return;
}
if (![arrList containsObject:fileUrl]) {
[arrList addObject:fileUrl];
}
[NSThread detachNewThreadSelector:@selector(downloadMp3) toTarget:self withObject:nil];
}
-(void)downloadMp3{
NSString *urlString = [self getMp3Url];
while (urlString!=nil && [urlString length]>0) {
@try{
dispatch_async(kBgQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
if ([data length]==0) {
NSLog(@"%@ ++++++++++++++++++++++++++++++++++++++",urlString);
}else{
NSLog(@"%@ ++++++++++++++++++++++++++++++++++++++ %lu",urlString, [data length]);
}
});
[NSThread sleepForTimeInterval:0.1];
}@catch (NSException * e) {
break;
}
urlString = [self getMp3Url];
}
}
-(NSString *)getMp3Url{
NSMutableString *str=[[NSMutableString alloc] init];
@synchronized(arrList){
if([arrList count]==0)return nil;
while(arrList.count>5)[arrList removeObjectAtIndex:0];
[str setString:arrList[0]] ;
[arrList removeObjectAtIndex:0];
return str;
}
}
@end