83 lines
2.6 KiB
Swift
83 lines
2.6 KiB
Swift
//
|
|
// SaveToPhotosActivity.swift
|
|
// Tusker
|
|
//
|
|
// Created by Shadowfacts on 1/2/23.
|
|
// Copyright © 2023 Shadowfacts. All rights reserved.
|
|
//
|
|
|
|
import UIKit
|
|
import UniformTypeIdentifiers
|
|
import Photos
|
|
|
|
class SaveToPhotosActivity: UIActivity {
|
|
|
|
override class var activityCategory: UIActivity.Category {
|
|
return .action
|
|
}
|
|
override var activityType: UIActivity.ActivityType? {
|
|
return .saveToPhotos
|
|
}
|
|
|
|
override var activityTitle: String? {
|
|
return "Save to Photos"
|
|
}
|
|
override var activityImage: UIImage? {
|
|
// Just using the symbol image directly causes it to be stretched.
|
|
let symbol = UIImage(systemName: "square.and.arrow.down", withConfiguration: UIImage.SymbolConfiguration(scale: .large))!
|
|
let format = UIGraphicsImageRendererFormat()
|
|
#if os(visionOS)
|
|
format.scale = 2
|
|
#else
|
|
format.scale = UIScreen.main.scale
|
|
#endif
|
|
return UIGraphicsImageRenderer(size: CGSize(width: 76, height: 76), format: format).image { ctx in
|
|
let rect = AVMakeRect(aspectRatio: symbol.size, insideRect: CGRect(x: 0, y: 0, width: 76, height: 76))
|
|
symbol.draw(in: rect)
|
|
}
|
|
}
|
|
|
|
override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
|
|
return activityItems.contains(where: {
|
|
if let url = $0 as? URL,
|
|
let type = UTType(filenameExtension: url.pathExtension){
|
|
return type.conforms(to: .movie) || type.conforms(to: .video) || type.conforms(to: .image)
|
|
} else {
|
|
return false
|
|
}
|
|
})
|
|
}
|
|
|
|
private var url: URL?
|
|
private var type: UTType?
|
|
|
|
override func prepare(withActivityItems activityItems: [Any]) {
|
|
for case let url as URL in activityItems {
|
|
self.url = url
|
|
type = UTType(filenameExtension: url.pathExtension)!
|
|
}
|
|
}
|
|
|
|
override func perform() {
|
|
guard let url,
|
|
let type else {
|
|
return
|
|
}
|
|
PHPhotoLibrary.requestAuthorization(for: .addOnly) { status in
|
|
guard case .authorized = status else {
|
|
return
|
|
}
|
|
PHPhotoLibrary.shared().performChanges {
|
|
if type.conforms(to: .movie) || type.conforms(to: .video) {
|
|
_ = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
|
|
} else {
|
|
_ = PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: url)
|
|
}
|
|
} completionHandler: { _, _ in
|
|
self.activityDidFinish(true)
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|