Download file from server using Swift

Hi, I have a whole bunch of .mp3 files that I want to use with NSFileManager and store in a folder with documents. Is there a way to upload .mp3 files on the Internet and then save it in a folder with documents? This is what I use for the local file.

let filemanager = NSFileManager.defaultManager() let documentsPath : AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0] let destinationPath:NSString = documentsPath.stringByAppendingString("/Attention.mp3") if (!filemanager.fileExistsAtPath(destinationPath)) { var theError: NSError? let fileForCopy = NSBundle.mainBundle().pathForResource("Attention",ofType:"mp3") filemanager.copyItemAtPath(fileForCopy!,toPath:destinationPath, error: &theError) if (theError == nil) { println("The music files has been saved.") } else { println("Error") } } else { println("The files already exist") } 
+6
source share
1 answer

Xcode 8.3.2 • Swift 3.1

 if let audioUrl = URL(string: "http://freetone.org/ring/stan/iPhone_5-Alarm.mp3") { // create your document folder url let documentsUrl = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) // your destination file url let destination = documentsUrl.appendingPathComponent(audioUrl.lastPathComponent) print(destination) // check if it exists before downloading it if FileManager().fileExists(atPath: destination.path) { print("The file already exists at path") } else { // if the file doesn't exist // just download the data from your url URLSession.shared.downloadTask(with: audioUrl, completionHandler: { (location, response, error) in // after downloading your data you need to save it to your destination url guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let mimeType = response?.mimeType, mimeType.hasPrefix("audio"), let location = location, error == nil else { return } do { try FileManager.default.moveItem(at: location, to: destination) print("file saved") } catch { print(error) } }).resume() } } 
+18
source

Source: https://habr.com/ru/post/979828/


All Articles