2015-02-03 8 views
6

Я пишу приложение, где я могу ввести URL-адрес mp3-файла из Интернета, и когда я нажму скачать, приложение загрузит его в приложении. Кто-нибудь может мне помочь ? Я новичок в разработке ios. Я пытаюсь узнать SwiftXcode: Скачать mp3 файл

ответ

18

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, completionHandler: { (location, response, error) -> Void 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 let error as NSError { 
       print(error.localizedDescription) 
      } 
     }).resume() 
    } 
} 

Xcode 7.2.1 • Swift 2.1.1

// First you need to create your audio url 

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

     // then lets create your document folder url 
     let documentsDirectoryURL = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! 

     // lets create your destination file url 
     let destinationUrl = documentsDirectoryURL.URLByAppendingPathComponent(audioUrl.lastPathComponent ?? "audio.mp3") 
     print(destinationUrl) 

     // to check if it exists before downloading it 
     if NSFileManager().fileExistsAtPath(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 
      NSURLSession.sharedSession().downloadTaskWithURL(audioUrl, completionHandler: { (location, response, error) -> Void in 
       guard let location = location where error == nil else { return } 
       do { 
        // after downloading your file you need to move it to your destination url 
        try NSFileManager().moveItemAtURL(location, toURL: destinationUrl) 
        print("File moved to documents folder") 
       } catch let error as NSError { 
        print(error.localizedDescription) 
       } 
      }).resume() 
     } 
    } 
+1

Спасибо. Большая часть кода работает За исключением ** writeToURL ** не работает. Я использовал ** writeToFile **, и это сработало для меня – Nick