栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Swift从服务器下载文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Swift从服务器下载文件

编辑/更新: Xpre 11.5•Swift 5.2

import UIKitimport AVFoundationclass ViewController: UIViewController {    var player: AVPlayer!    override func viewDidLoad() {        super.viewDidLoad()        let alarm = URL(string: "https://www.ringtonemobi.com/storage/upload/user_id_1/iphone-5-alarm-2016-08-21-01-49-25.mp3")!        do { try alarm.download(to: .documentDirectory) { url, error in     guard let url = url else { return }     self.player = AVPlayer(url: url)     self.player.play() }        } catch { print(error)        }    }}

import Foundationextension URL {    func download(to directory: FileManager.SearchPathDirectory, using fileName: String? = nil, overwrite: Bool = false, completion: @escaping (URL?, Error?) -> Void) throws {        let directory = try FileManager.default.url(for: directory, in: .userDomainMask, appropriateFor: nil, create: true)        let destination: URL        if let fileName = fileName { destination = directory     .appendingPathComponent(fileName)     .appendingPathExtension(self.pathExtension)        } else { destination = directory .appendingPathComponent(lastPathComponent)        }        if !overwrite, FileManager.default.fileExists(atPath: destination.path) { completion(destination, nil) return        }        URLSession.shared.downloadTask(with: self) { location, _, error in guard let location = location else {     completion(nil, error)     return } do {     if overwrite, FileManager.default.fileExists(atPath: destination.path) {         try FileManager.default.removeItem(at: destination)     }     try FileManager.default.moveItem(at: location, to: destination)     completion(destination, nil) } catch {     print(error) }        }.resume()    }}


原始答案

Xpre 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.default.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()    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636336.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号