11

I am writing an app where, I can enter URL of a mp3 file from web and when i click download, the app will download it in the app. Can someone help me ? I am new to ios development. I am trying to learn Swift

Nick
  • 183
  • 1
  • 3
  • 6

1 Answers1

32

Xcode 8 • Swift 3

if let audioUrl = URL(string: "http://freetone.org/ring/stan/iPhone_5-Alarm.mp3") {

    // then lets create your document folder url
    let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

    // lets create your destination file url
    let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
    print(destinationUrl)

    // to check if it exists before downloading it
    if FileManager.default.fileExists(atPath: destinationUrl.path) {
        print("The file already exists at path")

        // if the file doesn't exist
    } else {

        // you can use NSURLSession.sharedSession to download the data asynchronously
        URLSession.shared.downloadTask(with: audioUrl) { location, response, error in
            guard let location = location, error == nil else { return }
            do {
                // after downloading your file you need to move it to your destination url
                try FileManager.default.moveItem(at: location, to: destinationUrl)
                print("File moved to documents folder")
            } catch {
                print(error)
            }
        }.resume()
    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • 2
    Thank You. Most of the code worked Except **writeToURL** didn't work. I used **writeToFile** and that worked for me – Nick Feb 14 '15 at 14:37
  • @Leo if i have to give the option of multiple downloadable files then? the problem is that urlsForDirectory is an array of Urls how can i assign index to it, your code only picks up the first index and then append it to array's last component. if i add .index to it then it converts it to an Int type which doesn't recognize array of urls – Usama bin Attique Jun 19 '18 at 11:12