Skip to content

Commit 7223867

Browse files
committed
Add MediaResponse in iOS / refactor in swift
1 parent 391f9dd commit 7223867

File tree

3 files changed

+143
-78
lines changed

3 files changed

+143
-78
lines changed

ios/CropImageController.swift

Lines changed: 0 additions & 8 deletions
This file was deleted.

ios/MediaResponse.swift

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
//
2+
// MediaResponse.swift
3+
// react-native-multiple-image-picker
4+
//
5+
// Created by Donquijote on 02/04/2023.
6+
//
7+
8+
import TLPhotoPicker
9+
import Photos
10+
import Foundation
11+
12+
public struct MediaResponse {
13+
14+
public enum MediaType: String {
15+
case image, video
16+
}
17+
18+
// public var path: String = "";
19+
// public var localIdentifier: String = "";
20+
// public var fileName: String = "";
21+
// public var width: NSNumber = 0;
22+
// public var height: NSNumber = 0;
23+
// public var mime: String = "";
24+
// public var creationDate: Date;
25+
// public var type: MediaType = .image;
26+
//
27+
public var data: NSDictionary? = nil
28+
29+
30+
init(filePath: String?, mime: String?, withTLAsset TLAsset: TLPHAsset, isExportThumbnail: Bool = false) {
31+
var asset = TLAsset.phAsset
32+
if(asset != nil){
33+
var media = [
34+
"path": filePath! as String,
35+
"localIdentifier": asset?.localIdentifier ?? "" as String,
36+
"fileName":TLAsset.originalFileName!,
37+
"width": Int(asset?.pixelWidth ?? 0 ) as NSNumber,
38+
"height": Int(asset?.pixelHeight ?? 0 ) as NSNumber,
39+
"mime": mime!,
40+
"creationDate": asset?.creationDate ?? "",
41+
"type": asset?.mediaType == .video ? "video" : "image",
42+
] as [String : Any]
43+
44+
// check video type
45+
if(asset?.mediaType == .video){
46+
//get video's thumbnail
47+
if(isExportThumbnail){
48+
media["thumbnail"] = getThumbnail(from: filePath!, in: 0.1)
49+
}
50+
//get video size
51+
TLAsset.videoSize { size in
52+
media["size"] = size
53+
}
54+
media["duration"] = asset?.duration
55+
}else{
56+
TLAsset.photoSize { photoSize in
57+
media["size"] = photoSize
58+
}
59+
}
60+
self.data = NSDictionary(dictionary: media)
61+
}
62+
}
63+
64+
65+
}
66+
67+
68+
func getThumbnail(from moviePath: String, in seconds: Double) -> String? {
69+
let filepath = moviePath.replacingOccurrences(
70+
of: "file://",
71+
with: "")
72+
let vidURL = URL(fileURLWithPath: filepath)
73+
74+
let asset = AVURLAsset(url: vidURL, options: nil)
75+
let generator = AVAssetImageGenerator(asset: asset)
76+
generator.appliesPreferredTrackTransform = true
77+
78+
var _: Error? = nil
79+
let time = CMTimeMake(value: 1, timescale: 60)
80+
81+
var imgRef: CGImage? = nil
82+
do {
83+
imgRef = try generator.copyCGImage(at: time, actualTime: nil)
84+
} catch _ {
85+
}
86+
var thumbnail: UIImage? = nil
87+
if let imgRef = imgRef {
88+
thumbnail = UIImage(cgImage: imgRef)
89+
}
90+
// save to temp directory
91+
let tempDirectory = FileManager.default.urls(
92+
for: .cachesDirectory,
93+
in: .userDomainMask).map(\.path).last
94+
95+
let data = thumbnail?.jpegData(compressionQuality: 1.0)
96+
let fileManager = FileManager.default
97+
let fullPath = URL(fileURLWithPath: tempDirectory ?? "").appendingPathComponent("thumb-\(ProcessInfo.processInfo.globallyUniqueString).jpg").path
98+
fileManager.createFile(atPath: fullPath, contents: data, attributes: nil)
99+
return fullPath;
100+
101+
}

ios/MultipleImagePicker.swift

Lines changed: 42 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ class MultipleImagePicker: NSObject, TLPhotosPickerViewControllerDelegate,UINavi
1818
var options = NSMutableDictionary();
1919
var videoAssets = [PHAsset]()
2020
var videoCount = 0
21+
var imageRequestOptions = PHImageRequestOptions();
22+
var videoRequestOptions = PHVideoRequestOptions.init()
23+
24+
2125
// controller
2226

2327

@@ -84,6 +88,15 @@ class MultipleImagePicker: NSObject, TLPhotosPickerViewControllerDelegate,UINavi
8488
}
8589
}
8690

91+
// set image / video request option.
92+
self.imageRequestOptions.deliveryMode = .fastFormat;
93+
self.imageRequestOptions.resizeMode = .fast;
94+
self.imageRequestOptions.isNetworkAccessAllowed = true
95+
self.imageRequestOptions.isSynchronous = false
96+
self.videoRequestOptions.version = PHVideoRequestOptionsVersion.current
97+
self.videoRequestOptions.deliveryMode = PHVideoRequestOptionsDeliveryMode.automatic
98+
self.videoRequestOptions.isNetworkAccessAllowed = true
99+
87100
//config options
88101
MultipleImagePickerConfigure.tapHereToChange = self.options["tapHereToChange"] as! String
89102
MultipleImagePickerConfigure.numberOfColumn = self.options["numberOfColumn"] as! Int;
@@ -173,41 +186,6 @@ class MultipleImagePicker: NSObject, TLPhotosPickerViewControllerDelegate,UINavi
173186
return media
174187
}
175188

176-
func getThumbnail(from moviePath: String, in seconds: Double) -> String? {
177-
let filepath = moviePath.replacingOccurrences(
178-
of: "file://",
179-
with: "")
180-
let vidURL = URL(fileURLWithPath: filepath)
181-
182-
let asset = AVURLAsset(url: vidURL, options: nil)
183-
let generator = AVAssetImageGenerator(asset: asset)
184-
generator.appliesPreferredTrackTransform = true
185-
186-
var _: Error? = nil
187-
let time = CMTimeMake(value: 1, timescale: 60)
188-
189-
var imgRef: CGImage? = nil
190-
do {
191-
imgRef = try generator.copyCGImage(at: time, actualTime: nil)
192-
} catch _ {
193-
}
194-
var thumbnail: UIImage? = nil
195-
if let imgRef = imgRef {
196-
thumbnail = UIImage(cgImage: imgRef)
197-
}
198-
// save to temp directory
199-
let tempDirectory = FileManager.default.urls(
200-
for: .cachesDirectory,
201-
in: .userDomainMask).map(\.path).last
202-
203-
let data = thumbnail?.jpegData(compressionQuality: 1.0)
204-
let fileManager = FileManager.default
205-
let fullPath = URL(fileURLWithPath: tempDirectory ?? "").appendingPathComponent("thumb-\(ProcessInfo.processInfo.globallyUniqueString).jpg").path
206-
fileManager.createFile(atPath: fullPath, contents: data, attributes: nil)
207-
return fullPath;
208-
209-
}
210-
211189
func shouldDismissPhotoPicker(withTLPHAssets: [TLPHAsset]) -> Bool {
212190
return false
213191
}
@@ -238,35 +216,45 @@ class MultipleImagePicker: NSObject, TLPhotosPickerViewControllerDelegate,UINavi
238216
self.getTopMostViewController()?.present(cropViewController, animated: true, completion: nil)
239217
}
240218

219+
func fetchAsset(TLAsset: TLPHAsset ,completion: @escaping (MediaResponse) -> Void) {
220+
let index = TLAsset.selectedOrder - 1;
221+
222+
TLAsset.tempCopyMediaFile(videoRequestOptions: self.videoRequestOptions, imageRequestOptions: self.imageRequestOptions, livePhotoRequestOptions: nil, exportPreset: AVAssetExportPresetHighestQuality, convertLivePhotosToJPG: true, progressBlock: { (progress) in
223+
}, completionBlock: { (filePath, fileType) in
224+
225+
let object = MediaResponse(filePath: filePath.absoluteString, mime: fileType, withTLAsset: TLAsset, isExportThumbnail: self.options["isExportThumbnail"] as! Bool)
226+
227+
DispatchQueue.main.async {
228+
completion(object)
229+
}
230+
})
231+
232+
}
233+
241234
func dismissPhotoPicker(withTLPHAssets: [TLPHAsset]) {
235+
236+
// check with asset picker
242237
if(withTLPHAssets.count == 0){
243238
self.resolve([]);
244239
dismissComplete()
245240
return;
246241
}
247242

243+
// count
248244
let withTLPHAssetsCount = withTLPHAssets.count;
249245
let selectedAssetsCount = self.selectedAssets.count;
250246

251-
//check difference
247+
// check difference
252248
if(withTLPHAssetsCount == selectedAssetsCount && withTLPHAssets[withTLPHAssetsCount - 1].phAsset?.localIdentifier == self.selectedAssets[selectedAssetsCount-1].phAsset?.localIdentifier){
249+
// if diff => close
253250
dismissComplete()
254251
return;
255252
}
256253

257254
let selections = NSMutableArray.init(array: withTLPHAssets);
258255
self.selectedAssets = withTLPHAssets
259256
//imageRequestOptions
260-
let imageRequestOptions = PHImageRequestOptions();
261-
imageRequestOptions.deliveryMode = .fastFormat;
262-
imageRequestOptions.resizeMode = .fast;
263-
imageRequestOptions.isNetworkAccessAllowed = true
264-
imageRequestOptions.isSynchronous = false
265-
266-
let videoRequestOptions = PHVideoRequestOptions.init()
267-
videoRequestOptions.version = PHVideoRequestOptionsVersion.current
268-
videoRequestOptions.deliveryMode = PHVideoRequestOptionsDeliveryMode.automatic
269-
videoRequestOptions.isNetworkAccessAllowed = true
257+
270258

271259
//add loading view
272260
let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)
@@ -287,40 +275,24 @@ class MultipleImagePicker: NSObject, TLPhotosPickerViewControllerDelegate,UINavi
287275
alert.view.addSubview(loadingIndicator)
288276

289277
self.getTopMostViewController()?.present(alert, animated: true, completion: {
278+
290279
let group = DispatchGroup()
280+
291281
for TLAsset in withTLPHAssets {
292282
group.enter()
293-
let asset = TLAsset.phAsset
294-
let index = TLAsset.selectedOrder - 1;
295-
296-
TLAsset.tempCopyMediaFile(videoRequestOptions: videoRequestOptions, imageRequestOptions: imageRequestOptions, livePhotoRequestOptions: nil, exportPreset: AVAssetExportPresetHighestQuality, convertLivePhotosToJPG: true, progressBlock: { (progress) in
297-
print("progress: ", progress)
298-
}, completionBlock: { (filePath, fileType) in
299-
let object = NSDictionary(dictionary: self.createAttachmentResponse(
300-
filePath: filePath.absoluteString,
301-
withFilename:TLAsset.originalFileName,
302-
withType: fileType,
303-
withAsset: asset!,
304-
withTLAsset: TLAsset
305-
)!);
306-
307-
selections[index] = object as Any;
283+
self.fetchAsset(TLAsset: TLAsset) { object in
284+
// check nil object response
285+
if(object != nil) {
286+
selections[index] = object as MediaResponse;
287+
}
308288
group.leave();
309-
})
289+
}
310290
}
311291

312292
group.notify(queue: .main){ [self] in
313293
resolve(selections);
314294
DispatchQueue.main.async {
315295
alert.dismiss(animated: true, completion: {
316-
if((self.options["singleSelectedMode"] as! Bool) && (self.options["isCrop"] as! Bool)){
317-
let image = withTLPHAssets.first?.fullResolutionImage
318-
319-
if(image != nil){
320-
self.presentCropViewController(image: image!)
321-
return;
322-
}
323-
}
324296
self.dismissComplete()
325297
})
326298
}

0 commit comments

Comments
 (0)