Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/114.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 多个URL的数组';NSS文件管理器Swift_Ios_Swift_Nsfilemanager - Fatal编程技术网

Ios 多个URL的数组';NSS文件管理器Swift

Ios 多个URL的数组';NSS文件管理器Swift,ios,swift,nsfilemanager,Ios,Swift,Nsfilemanager,如何添加多个URL?我想知道如何用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")

如何添加多个URL?我想知道如何用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")
            }
        }
    }
}

在这种情况下,我认为应该使用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")
}

在这种情况下,我认为应该使用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下载怎么样?我如何保存文件?你们是一个了不起的家伙。非常感谢你的帮助!圣诞快乐。在swift 3中使用Alamofire下载怎么样?我如何保存文件?顺便说一下,我不知道您将发出多少个请求,但值得注意的是,如果您有很多请求,您可能需要限制在任何给定时间尝试运行的请求数(例如,3到5之间)。如果您不这样做,并且您通过慢速连接发出了太多请求,则后面的一些请求将开始超时。典型的解决方案是将它们包装在异步
NSOperation
子类中,并将
NSOperationQueue
与特定的
maxConcurrentOperationCount
一起使用。或者,如果你想在应用程序退出后继续,你可以使用后台会话。顺便说一句,我不知道你将发出多少个请求,但值得注意的是,如果你有很多请求,你可能需要限制在任何给定时间尝试运行的请求数量(例如,3到5个之间的请求)。如果您不这样做,并且您通过慢速连接发出了太多请求,则后面的一些请求将开始超时。典型的解决方案是将它们包装在异步
NSOperation
子类中,并将
NSOperationQueue
与特定的
maxConcurrentOperationCount
一起使用。或者,如果你想让它们在应用程序退出后继续,你可以使用后台会话。