与Alamofire下载Access文件未知文件名downloadsdirectory

问题描述 投票:0回答:1

我有iOS设备上使用金属呈现OBJ文件的应用程序。我想补充的功能,为用户在线插入OBJ文件的URL和渲染。我使用alamofire,我不知道我怎么会访问一次下载的文件,因为我不知道该文件的名称。

let destination = DownloadRequest.suggestedDownloadDestination(for: .downloadsDirectory)

let modelUrl = URL(string: "https://drive.google.com/file/d/110KRnku3N_K_EIN-ZLYXK128zjMqxGLM/view?usp=sharing")

Alamofire.download(
    modelUrl!,
    method: .get,
    parameters: Parameters.init(),
    encoding: JSONEncoding.default,
    headers: nil,
    to: destination).downloadProgress(closure: { (progress) in
        //progress closure
    }).response(completionHandler: { (DefaultDownloadResponse) in
        //here you able to access the DefaultDownloadResponse
        //result closure
    })
let file = try? String(contentsOf: URL(string: (NSSearchPathForDirectoriesInDomains(.downloadsDirectory, .userDomainMask, true)[0]))!)

我也相当肯定我的检索文件将无法正常工作的方法,但我不知道如何搜索文件目录的特定文件。我有工作的文件是在项目中在Xcode .OBJ文件,我只是用这个。

let assetURL = Bundle.main.url(forResource: modelName, withExtension: "obj")
ios swift networking download alamofire
1个回答
0
投票

Bundle.main不会document directory返回文件,它是使用你把你的主束(里面的Xcode开发虽然通常情况下)的文件。您需要使用FileManager访问document directory文件。您可以使用此功能在您的文档目录中搜索文件。

func getFilePathInDocuments(fileName:String) -> String {
    let path        = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url         = URL(fileURLWithPath: path)
    let fileManager = FileManager.default
    let filePath    = url.appendingPathComponent(fileName).path

    if (fileManager.fileExists(atPath: filePath)) {
        return filePath
    }else{
        return ""
    }
}

这是你如何称呼它:

let foundPath = getFilePathInDocuments(fileName: "fileName.obj")

更新:

你可以给一个fileNameAlmofire,你会从中接收下载网址了。

let destinationPath: DownloadRequest.DownloadFileDestination = { _, _ in
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0];
    let fileURL = documentsURL.appendingPathComponent("fileName")
    return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}

Alamofire.download(url, to: destinationPath)
    .downloadProgress { progress in
    }
    .responseData { response in
}

为了让下载的文件目录URL使用response.destinationURL

© www.soinside.com 2019 - 2024. All rights reserved.