栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

多个URL的NSFileManager Swift数组

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

多个URL的NSFileManager Swift数组

在这种情况下,我认为您应该使用NSURLSession.sharedSession()。dataTaskWithURL从链接中进行多次下载,但要保持下载操作异步。您需要向其添加一个回调块。您应该执行以下操作:

let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.documentDirectory, inDomains: .UserDomainMask).first as NSURLlet musicArray:[String] = ["http://freetone.org/ring/stan/iPhone_5-Alarm.mp3","http://freetone.org/ring/stan2/Samsung_Galaxy_S4-SMS.mp3","https://www.sounddogs.com/sound-effects/25/mp3/235178_SOUNDDOGS__al.mp3"]var musicUrls:[NSURL!]!// create a function to start the audio data downloadfunc getAudioDataFromUrl(audioUrl:NSURL, completion: ((data: NSData?) -> Void)) {    NSURLSession.sharedSession().dataTaskWithURL(audioUrl) { (data, response, error) in        completion(data:  data)    }.resume()}// create another function to save the audio datafunc saveAudioData(audio:NSData, destination:NSURL) -> Bool {    if audio.writeToURL(destination, atomically: true) {        println("The file "(destination.lastPathComponent!.stringByDeletingPathExtension)" was successfully saved.")        return true    }    return false}// just convert your links to Urlsfunc linksToUrls(){    musicUrls = musicArray        .map() { NSURL(string: $0) }        .filter() { $0 != nil }}// create a loop to start downloading your urlsfunc startDownloadingUrls(){    for url in musicUrls {        let destinationUrl = documentsUrl.URLByAppendingPathComponent(url.lastPathComponent!)        if NSFileManager().fileExistsAtPath(destinationUrl.path!) { println("The file "(destinationUrl.lastPathComponent!.stringByDeletingPathExtension)" already exists at path.")        } else { println("Started downloading "(url.lastPathComponent!.stringByDeletingPathExtension)".") getAudioDataFromUrl(url) { data in     dispatch_async(dispatch_get_main_queue()) {         println("Finished downloading "(url.lastPathComponent!.stringByDeletingPathExtension)".")         println("Started saving "(url.lastPathComponent!.stringByDeletingPathExtension)".")         if self.saveAudioData(data!, destination: self.documentsUrl.URLByAppendingPathComponent(url.lastPathComponent!) ) {  // do what ever if writeToURL was successful         } else {  println("The File "(url.lastPathComponent!.stringByDeletingPathExtension)" was not saved.")         }     } }        }    }}override func viewDidLoad() {    super.viewDidLoad()    // Do any additional setup after loading the view, typically from a nib.    println("Begin of pre")    linksToUrls()    startDownloadingUrls()    println("End of pre")}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/616414.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号