2014-12-18 3 views
6

Привет, У меня есть целая группа файлов .mp3, которую я хочу использовать с NSFileManager и хранить в папке с документами. Есть ли способ загрузить файлы .mp3 в Интернете, а затем сохранить его в папке с документами? Это то, что я использую для локального файла.Загрузить файл с сервера с помощью Swift

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

Как указать файлы, которые вы хотите загрузить? –

+0

@ThomasKilian Ну локально, вы можете сделать fileForCopy = NSBundle.mainBundle(). PathForResource («Attention», ofType: «mp3») –

+0

@ThomasKilian Но что, если у меня есть URL-адрес и вы хотите загрузить его оттуда? –

ответ

18

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() 
    } 
} 
+0

Вот если я хочу использовать локальный файл. Я уже знаю, как это сделать. Мне интересно, как я могу скачать .mp3 по ссылке и сохранить ее в папку для скачивания. –

+0

Ты потрясающий чувак! Именно то, что я искал. Просто быстрый вопрос, что, если у меня было несколько ссылок? Могу ли я просто бросить их в массив каким-то образом? –

+0

Не стесняйтесь, чтобы открыть другой вопрос. Я постараюсь выяснить это. –

Смежные вопросы