ноль конечно. return destinationFileUrl
, используйте его для инициализации PDF, получите ноль.
возвращается, пока задача еще выполняется, поэтому файл в пути не существует.
Поскольку загрузка является асинхронным действием.
Итак, завершениеHandler закрывается для.
Обычно, превращайте этот
public func downloadData(urlString : String,downloadType : String)->URL?{
let documentsUrl:URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first as URL!
var destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.pdf")
try? FileManager.default.removeItem(at: destinationFileUrl)
guard let url = URL(string: urlString)else{
return nil
}
let urlSession = URLSession(configuration: .default)
let downloadTask = urlSession.downloadTask(with: url) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
if downloadType == "cache" {
do {
try? FileManager.default.removeItem(at: destinationFileUrl)
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
}
} else {
print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
}
}
downloadTask.resume()
return destinationFileUrl
}
в
public func downloadData(urlString : String,downloadType : String, completionHandler: @escaping (URL) -> Void){
let documentsUrl:URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first as URL!
var destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.pdf")
try? FileManager.default.removeItem(at: destinationFileUrl)
guard let url = URL(string: urlString)else{
return nil
}
let urlSession = URLSession(configuration: .default)
let downloadTask = urlSession.downloadTask(with: url) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
if downloadType == "cache" {
do {
try? FileManager.default.removeItem(at: destinationFileUrl)
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
completionHandler(destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
}
} else {
print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
}
}
downloadTask.resume()
}
При обратном вызове завершениеHandler, инициализация PDF