/
DocumentPickerModule.swift
172 lines (146 loc) · 5.14 KB
/
DocumentPickerModule.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import ExpoModulesCore
import UIKit
import MobileCoreServices
struct PickingContext {
let promise: Promise
let options: DocumentPickerOptions
let delegate: DocumentPickingDelegate
}
public class DocumentPickerModule: Module, PickingResultHandler {
private var pickingContext: PickingContext?
public func definition() -> ModuleDefinition {
Name("ExpoDocumentPicker")
AsyncFunction("getDocumentAsync") { (options: DocumentPickerOptions, promise: Promise) in
if pickingContext != nil {
throw PickingInProgressException()
}
guard let currentVc = appContext?.utilities?.currentViewController() else {
throw MissingViewControllerException()
}
let documentPickerVC = createDocumentPicker(with: options)
let pickerDelegate = DocumentPickingDelegate(resultHandler: self)
pickingContext = PickingContext(promise: promise, options: options, delegate: pickerDelegate)
documentPickerVC.delegate = pickerDelegate
documentPickerVC.presentationController?.delegate = pickerDelegate
documentPickerVC.allowsMultipleSelection = options.multiple
if UIDevice.current.userInterfaceIdiom == .pad {
let viewFrame = currentVc.view.frame
documentPickerVC.popoverPresentationController?.sourceRect = CGRect(
x: viewFrame.midX,
y: viewFrame.maxY,
width: 0,
height: 0
)
documentPickerVC.popoverPresentationController?.sourceView = currentVc.view
documentPickerVC.modalPresentationStyle = .pageSheet
}
currentVc.present(documentPickerVC, animated: true)
}.runOnQueue(.main)
}
func didPickDocumentsAt(urls: [URL]) {
guard let options = self.pickingContext?.options,
let promise = self.pickingContext?.promise else {
log.error("Picking context has been lost.")
return
}
pickingContext = nil
do {
if options.multiple {
let assets = try urls.map {
try readDocumentDetails(
documentUrl: $0,
copy: options.copyToCacheDirectory
)
}
promise.resolve(DocumentPickerResponse(assets: assets))
} else {
let asset = try readDocumentDetails(
documentUrl: urls[0],
copy: options.copyToCacheDirectory
)
promise.resolve(DocumentPickerResponse(assets: [asset]))
}
} catch {
promise.reject(error)
}
}
func didCancelPicking() {
guard let context = pickingContext else {
log.error("Picking context lost")
return
}
pickingContext = nil
context.promise.resolve(DocumentPickerResponse(canceled: true))
}
private func getFileSize(path: URL) -> Int? {
guard let resource = try? path.resourceValues(forKeys: [.fileSizeKey, .isDirectoryKey]) else {
return 0
}
if let isDirectory = resource.isDirectory {
if !isDirectory {
return resource.fileSize
}
}
guard let contents = try? FileManager.default.contentsOfDirectory(atPath: path.absoluteString) else {
return 0
}
let folderSize = contents.reduce(0) { currentSize, file in
let fileSize = getFileSize(path: path.appendingPathComponent(file)) ?? 0
return currentSize + fileSize
}
return folderSize
}
private func readDocumentDetails(documentUrl: URL, copy: Bool) throws -> DocumentInfo {
let pathExtension = documentUrl.pathExtension
var newUrl = documentUrl
guard let fileSystem = self.appContext?.fileSystem else {
throw Exceptions.FileSystemModuleNotFound()
}
guard let fileSize = try? getFileSize(path: documentUrl) else {
throw InvalidFileException()
}
if copy {
let directory = fileSystem.cachesDirectory.appending("DocumentPicker")
let path = fileSystem.generatePath(inDirectory: directory, withExtension: pathExtension)
newUrl = URL(fileURLWithPath: path)
try FileManager.default.copyItem(at: documentUrl, to: newUrl)
}
let mimeType = self.getMimeType(from: pathExtension)
return DocumentInfo(
uri: newUrl.absoluteString,
name: documentUrl.lastPathComponent,
size: fileSize,
mimeType: mimeType
)
}
private func getMimeType(from pathExtension: String) -> String? {
if #available(iOS 14, *) {
return UTType(filenameExtension: pathExtension)?.preferredMIMEType
} else {
if let uti = UTTypeCreatePreferredIdentifierForTag(
kUTTagClassFilenameExtension,
pathExtension as NSString, nil
)?.takeRetainedValue() {
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
}
return nil
}
}
private func createDocumentPicker(with options: DocumentPickerOptions) -> UIDocumentPickerViewController {
if #available(iOS 14.0, *) {
let utTypes = options.type.compactMap { $0.toUTType() }
return UIDocumentPickerViewController(
forOpeningContentTypes: utTypes,
asCopy: true
)
} else {
let utiTypes = options.type.map { $0.toUTI() }
return UIDocumentPickerViewController(
documentTypes: utiTypes,
in: .import
)
}
}
}