【问题标题】:Array of multiple URL's NSFileManager Swift多个 URL 的 NSFileManager Swift 数组
【发布时间】:2015-02-23 08:44:10
【问题描述】:

如何添加多个 URL?我想知道如何快速将其设置为数组。

if let audioUrl = NSURL(string: "http://freetone.org/ring/stan/iPhone_5-Alarm.mp3") {
    println("LOADING AUDIO")
    if let myAudioDataFromUrl = NSData(contentsOfURL: audioUrl){
        println("AUDIO LOADED")
        let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
        let destinationUrl = documentsUrl.URLByAppendingPathComponent(audioUrl.lastPathComponent!)
        println(destinationUrl)

        if NSFileManager().fileExistsAtPath(destinationUrl.path!) {
            println("The file already exists at path")
        } else {
            if myAudioDataFromUrl.writeToURL(destinationUrl, atomically: true) {
                println("file saved")
            } else {
                println("error saving file")
            }
        }
    }
}

【问题讨论】:

  • 顺便说一下,我不知道你要发出多少这样的请求,但值得注意的是,如果你有很多,你可能想限制你尝试的次数在任何给定时间运行(例如 3 到 5 之间的某个时间)。如果您不这样做并且您通过慢速连接发出任何请求,则后面的一些请求将开始超时。典型的解决方案是将这些包装在异步NSOperation 子类中,并将NSOperationQueue 与特定的maxConcurrentOperationCount 一起使用。或者,如果您希望它们在应用退出后继续,您可以使用后台会话。

标签: ios swift nsfilemanager


【解决方案1】:

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

let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as NSURL
let 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 download
func 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 data
func 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 Urls
func linksToUrls(){
    musicUrls = musicArray
        .map() { NSURL(string: $0) }
        .filter() { $0 != nil }
}

// create a loop to start downloading your urls
func 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 code")
    linksToUrls()
    startDownloadingUrls()
    println("End of code")
}

【讨论】:

  • 你是一个了不起的人。非常感谢您的帮助!圣诞快乐。
  • 那么在 swift 3 中使用 Alamofire 下载如何,我如何保存文件?
猜你喜欢
  • 2014-09-01
  • 1970-01-01
  • 2015-12-18
  • 2015-07-13
  • 2014-12-10
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多