-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
GalPlugin.swift
217 lines (196 loc) · 7.34 KB
/
GalPlugin.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import Photos
#if os(iOS)
import Flutter
import UIKit
#else
import Cocoa
import FlutterMacOS
#endif
public class GalPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
#if os(iOS)
let messenger = registrar.messenger()
#else
let messenger = registrar.messenger
#endif
let channel = FlutterMethodChannel(name: "gal", binaryMessenger: messenger)
let instance = GalPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "putVideo", "putImage":
let args = call.arguments as! [String: Any]
putMedia(
path: args["path"] as! String,
album: args["album"] as? String,
isImage: call.method == "putImage"
) { _, error in
result(error == nil ? nil : self.handleError(error: error!))
}
case "putImageBytes":
let args = call.arguments as! [String: Any]
putMediaBytes(
bytes: (args["bytes"] as! FlutterStandardTypedData).data,
album: args["album"] as? String,
name: args["name"] as! String
) { _, error in
result(error == nil ? nil : self.handleError(error: error!))
}
case "open":
open { result(nil) }
case "hasAccess":
let args = call.arguments as! [String: Bool]
result(hasAccess(toAlbum: args["toAlbum"]!))
case "requestAccess":
let args = call.arguments as! [String: Bool]
let toAlbum = args["toAlbum"]!
hasAccess(toAlbum: toAlbum)
? result(true)
: requestAccess(
toAlbum: toAlbum,
completion: { granted in
result(granted)
}
)
default:
result(FlutterMethodNotImplemented)
}
}
private func putMedia(
path: String, album: String?, isImage: Bool, completion: @escaping (Bool, Error?) -> Void
) {
let url = URL(fileURLWithPath: path)
writeContent(
assetChangeRequest: {
isImage
? PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: url)!
: PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)!
}, album: album, completion: completion
)
}
private func putMediaBytes(
bytes: Data, album: String?, name: String, completion: @escaping (Bool, Error?) -> Void
) {
writeContent(
assetChangeRequest: {
let request = PHAssetCreationRequest.forAsset()
let options = PHAssetResourceCreationOptions()
options.originalFilename = name
request.addResource(with: .photo, data: bytes, options: options)
return request
}, album: album, completion: completion
)
}
private func writeContent(
assetChangeRequest: @escaping () -> PHAssetChangeRequest,
album: String?,
completion: @escaping (Bool, Error?) -> Void
) {
if let album = album {
getAlbum(album: album) { collection, error in
if let error = error {
completion(false, error)
return
}
PHPhotoLibrary.shared().performChanges({
let albumChangeRequest = PHAssetCollectionChangeRequest(for: collection!)
albumChangeRequest!.addAssets(
[assetChangeRequest().placeholderForCreatedAsset!] as NSArray)
}, completionHandler: completion)
}
return
}
PHPhotoLibrary.shared().performChanges({ _ = assetChangeRequest() }, completionHandler: completion)
}
private func getAlbum(album: String, completion: @escaping (PHAssetCollection?, Error?) -> Void) {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", album)
let collections: PHFetchResult = PHAssetCollection.fetchAssetCollections(
with: .album, subtype: .any, options: fetchOptions
)
if let collection = collections.firstObject {
completion(collection, nil)
return
}
PHPhotoLibrary.shared().performChanges({
PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: album)
}, completionHandler: { success, error in
success
? self.getAlbum(album: album, completion: completion)
: completion(nil, error)
})
}
private func open(completion: @escaping () -> Void) {
#if os(iOS)
guard let url = URL(string: "photos-redirect://") else { return }
UIApplication.shared.open(url, options: [:]) { _ in completion() }
#else
guard let url = URL(string: "photos://") else { return }
NSWorkspace.shared.open(url)
completion()
#endif
}
private func hasAccess(toAlbum: Bool) -> Bool {
if #available(iOS 14, macOS 11, *) {
return toAlbum
? PHPhotoLibrary.authorizationStatus(for: .readWrite) == .authorized
|| PHPhotoLibrary.authorizationStatus(for: .readWrite) == .limited
: PHPhotoLibrary.authorizationStatus(for: .addOnly) == .authorized
}
return PHPhotoLibrary.authorizationStatus() == .authorized
}
/// If permissions have already been granted or denied by the user,
/// returns the result immediately, without displaying a dialog.
/// See: https://qiita.com/fuziki/items/87a3a1a8e481a1546b38
private func requestAccess(toAlbum: Bool, completion: @escaping (Bool) -> Void) {
if #available(iOS 14, macOS 11, *) {
PHPhotoLibrary.requestAuthorization(for: toAlbum ? .readWrite : .addOnly) { _ in
completion(self.hasAccess(toAlbum: toAlbum))
}
return
}
PHPhotoLibrary.requestAuthorization { _ in
completion(PHPhotoLibrary.authorizationStatus() == .authorized)
}
}
private func handleError(error: Error) -> FlutterError {
let error = error as NSError
let message = error.localizedDescription
let details = Thread.callStackSymbols
switch PHErrorCode(rawValue: error.code) {
case .accessRestricted, .accessUserDenied:
return FlutterError(code: "ACCESS_DENIED", message: message, details: details)
case .identifierNotFound, .multipleIdentifiersFound, .requestNotSupportedForAsset,
.videoConversionFailed, .unsupportedVideoCodec:
return FlutterError(code: "NOT_SUPPORTED_FORMAT", message: message, details: details)
case .notEnoughSpace:
return FlutterError(code: "NOT_ENOUGH_SPACE", message: message, details: details)
default:
return FlutterError(code: "UNEXPECTED", message: message, details: details)
}
}
}
/// Low iOS versions do not have an enum defined, so [rawValue] must be used.
/// If [rawValue] is not defined either, no handle is possible.
/// You can check Apple's documentation by replacing the [$caseName] of the following URL
/// Some documents are not provided by Apple.
/// https://developer.apple.com/documentation/photokit/phphotoserror/code/$caseName
enum PHErrorCode: Int {
// [PHPhotosError.identifierNotFound]
case identifierNotFound = 3201
// [PHPhotosError.multipleIdentifiersFound]
case multipleIdentifiersFound = 3202
// Apple has not released documentation.
case videoConversionFailed = 3300
// Apple has not released documentation.
case unsupportedVideoCodec = 3302
// [PHPhotosError.notEnoughSpace]
case notEnoughSpace = 3305
// [PHPhotosError.requestNotSupportedForAsset]
case requestNotSupportedForAsset = 3306
// [PHPhotosError.accessRestricted]
case accessRestricted = 3310
// [PHPhotosError.accessUserDenied]
case accessUserDenied = 3311
}