需求: daemon实现下载文件到/var/mobile/Media等系统目录
代码
dispatch_async(dispatch_get_global_queue(0, 0), ^{
while (true) {
NSLog(@"ABCD-开始下载");
if (![[NSFileManager defaultManager] fileExistsAtPath:@"/var/mobile/Media/test.zip"]) {
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); //创建信号量
NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithURL:[NSURL URLWithString:@"http://www.12306bypass.com/Download.aspx?name=12306Bypass.zip"] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"ABCD-下载失败");
}else{
NSError *error;
[[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL URLWithString:@"/var/mobile/Media/test.zip"] error:&error];
if(error){
NSLog(@"ABCD-%@",error);
}else{
NSLog(@"ABCD-下载成功");
}
}
dispatch_semaphore_signal(semaphore); //发送信号
}];
[task resume];
dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER); //等待
}
[NSThread sleepForTimeInterval:5];
}
});
CFRunLoopRun(); // keep it running in background
return 0;
结果
Error Domain=NSCocoaErrorDomain Code=262 “The file couldn’t be opened because the specified URL type isn’t supported.” UserInfo={NSURL=/var/mobile/Media/test.zip}