Guest User

Untitled

a guest
Jun 25th, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.72 KB | None | 0 0
  1. func createDocument(folderName: String ,completion: @escaping(Bool,String)->()){
  2. let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
  3. if let documentsDirectory = path{
  4. //
  5. let docDirectoryPath = documentsDirectory.appending(folderName)
  6. let fileManager = FileManager.default
  7.  
  8. if !fileManager.fileExists(atPath: docDirectoryPath) {
  9. do {
  10. try fileManager.createDirectory(atPath: docDirectoryPath,
  11. withIntermediateDirectories: true,
  12. attributes: nil)
  13. //return path on success
  14. completion(true,docDirectoryPath)
  15. return
  16. } catch {
  17. print("Error creating folder in documents dir: (error.localizedDescription)")
  18. completion(false,error.localizedDescription)
  19. return
  20. }
  21. }
  22. completion(true,docDirectoryPath)
  23. }
  24. }
  25.  
  26. func downloadDocument(){
  27.  
  28. createDocument(folderName: "/chat/doc") { (status, path) in
  29. if let docURL = self.documentURL{
  30. if status{
  31. //folder is created now download document
  32.  
  33. let docDownloadRef = Storage.storage().reference(forURL: docURL)
  34.  
  35. //get documents metadata from firebase to get document name
  36. docDownloadRef.getMetadata { metadata, error in
  37. if let error = error {
  38. // Uh-oh, an error occurred!
  39. } else {
  40. //get document name from metadata
  41.  
  42. if let fileName = metadata?.name{
  43.  
  44. //create file system url to store document
  45. let docsurl = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
  46.  
  47. let myurl = docsurl.appendingPathComponent("chat/(fileName)")
  48.  
  49. _ = docDownloadRef.write(toFile: myurl) { url, error in
  50. if let error = error {
  51. print(error.localizedDescription)
  52. } else {
  53. // Local file URL for document is returned
  54. print("doc url (url?.absoluteString)")
  55. }
  56. }
  57. }
  58. }
  59. }
  60.  
  61. }else{
  62. //folder is not created show document using online location
  63. }
  64. }
  65. }
  66. }
  67.  
  68. Ultimate goal is to achieve something like this "Documents/chat/doc/abc.doc"
Add Comment
Please, Sign In to add comment