Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

ios - Array of multiple URL's NSFileManager Swift

How would I go about adding multiple URL's? I wonder how I can set that up into an array with swift.

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")
            }
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In this case I think you should use NSURLSession.sharedSession().dataTaskWithURL to do multiple downloads from your links but keeping the download operation asynchronous. You need to add a callback block to it. You should do as follow:

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")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...