Как открыть файл.xls из контейнера данных с UIDocumentInteractionController в Swift?
func downloadTask(url: URL, fileName: String, fileNameWithExtension: String){
let fileManagerDefault = FileManager.default
var documentInteractionController : UIDocumentInteractionController!
// Create local path URL
let documentsUrl:URL = fileManagerDefault.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent(fileNameWithExtension)
print(destinationFileUrl)
print(url)
// Create session
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:url)
// if the file doesn't exist
// just download the data from your url
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
let alertController = UIAlertController(title:"Successfully downloaded", message:"Please open your downloaded file \""+fileNameWithExtension+"\".", preferredStyle:UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title:"Open in...", style: UIAlertActionStyle.cancel, handler: {
(action) in
//let filePath = NSURL(fileURLWithPath: String(describing: destinationFileUrl))
//print(filePath)
let fileExtension:CFString = destinationFileUrl.pathExtension as CFString //xls
let unmanagedFileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, nil)
let fileUTI = unmanagedFileUTI?.takeRetainedValue()/*com.microsoft.excel.xls*/
documentInteractionController = UIDocumentInteractionController(url: destinationFileUrl)
documentInteractionController.uti = fileUTI as String?
documentInteractionController.name = fileName
documentInteractionController.presentOptionsMenu(from: CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0), in: self.view, animated: true)
}))
alertController.addAction(UIAlertAction(title:"Cancel", style: UIAlertActionStyle.default, handler: nil))
self.present(alertController, animated:true, completion:nil)
}
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: %@", error?.localizedDescription as Any);
}
}
task.resume()
}
После завершения загрузки файлов в виде Excel в контейнере данных (файл ///var/mobile/ Containers / Data / Application/...), я пытаюсь открыть его с помощью одного из приложений для чтения, но когда я коснулся одного из приложения, есть ошибка сбоя.
Снимок экрана:
Что не так с этим кодом? Как это исправить?