swift - 自动保存实时照片
问题描述
Xcode 新手,尝试制作一个下载动态壁纸的应用程序。我使用来自 github 的 LivePhotoDemo 来编写所有代码。我的问题是,当页面加载时,它会显示实时照片,但在我的照片库中保存了两份副本而且我似乎无法弄清楚如何获得保存按钮来代替它(并且只有一份副本)
import UIKit
import Photos
import PhotosUI
import MobileCoreServices
struct FilePaths {
static let documentsPath : AnyObject = NSSearchPathForDirectoriesInDomains(.cachesDirectory,.userDomainMask,true)[0] as AnyObject
struct VidToLive {
static var livePath = FilePaths.documentsPath.appending("/")
}
}
class ViewController: UIViewController,
UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//@IBOutlet var livePhotoView: PHLivePhotoView!
@IBOutlet var livePhotoView: PHLivePhotoView!
{
didSet {
loadVideoWithVideoURL(Bundle.main.url(forResource: "video", withExtension: "mov")!)
}
}
func loadVideoWithVideoURL(_ videoURL: URL) {
livePhotoView.livePhoto = nil
let asset = AVURLAsset(url: videoURL)
let generator = AVAssetImageGenerator(asset: asset)
generator.appliesPreferredTrackTransform = true
let time = NSValue(time: CMTimeMakeWithSeconds(CMTimeGetSeconds(asset.duration)/2, preferredTimescale: asset.duration.timescale))
generator.generateCGImagesAsynchronously(forTimes: [time]) { [weak self] _, image, _, _, _ in
if let image = image, let data = UIImage(cgImage: image).pngData() {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let imageURL = urls[0].appendingPathComponent("image.jpg")
try? data.write(to: imageURL, options: [.atomic])
let image = imageURL.path
let mov = videoURL.path
let output = FilePaths.VidToLive.livePath
let assetIdentifier = UUID().uuidString
let _ = try? FileManager.default.createDirectory(atPath: output, withIntermediateDirectories: true, attributes: nil)
do {
try FileManager.default.removeItem(atPath: output + "/IMG.JPG")
try FileManager.default.removeItem(atPath: output + "/IMG.MOV")
} catch {
}
JPEG(path: image).write(output + "/IMG.JPG",
assetIdentifier: assetIdentifier)
QuickTimeMov(path: mov).write(output + "/IMG.MOV",
assetIdentifier: assetIdentifier)
//self?.livePhotoView.livePhoto = LPDLivePhoto.livePhotoWithImageURL(NSURL(fileURLWithPath: FilePaths.VidToLive.livePath.stringByAppendingString("/IMG.JPG")), videoURL: NSURL(fileURLWithPath: FilePaths.VidToLive.livePath.stringByAppendingString("/IMG.MOV")))
//self?.exportLivePhoto()
_ = DispatchQueue.main.sync {
PHLivePhoto.request(withResourceFileURLs: [ URL(fileURLWithPath: FilePaths.VidToLive.livePath + "/IMG.MOV"), URL(fileURLWithPath: FilePaths.VidToLive.livePath + "/IMG.JPG")],
placeholderImage: nil,
targetSize: self!.view.bounds.size,
contentMode: PHImageContentMode.aspectFit,
resultHandler: { (livePhoto, info) -> Void in
self?.livePhotoView.livePhoto = livePhoto
self?.exportLivePhoto()
})
}
}
}
}
@IBAction func Savephoto(_ sender: UIBarButtonItem){
}
func exportLivePhoto () {
PHPhotoLibrary.shared().performChanges({ () -> Void in
let creationRequest = PHAssetCreationRequest.forAsset()
let options = PHAssetResourceCreationOptions()
creationRequest.addResource(with: PHAssetResourceType.pairedVideo, fileURL: URL(fileURLWithPath: FilePaths.VidToLive.livePath + "/IMG.MOV"), options: options)
creationRequest.addResource(with: PHAssetResourceType.photo, fileURL: URL(fileURLWithPath: FilePaths.VidToLive.livePath + "/IMG.JPG"), options: options)
}, completionHandler: { (success, error) -> Void in
if !success {
NSLog((error?.localizedDescription)!)
}
})
}
}
我将主视图链接到顶部的 IBOutlet,将保存按钮链接到底部附近的 IBAction。除了几年前的一些 HTML 和 C++ 之外,我实际上对编码知之甚少。我只知道如何查看代码并尝试理解所有内容。有人可以告诉我我做错了什么以及在哪里。太感谢了!
解决方案
这里有一些事情可以让你摆脱困境。
问题 1:如何让我的保存按钮调用 exportLivePhoto():
您的按钮的 IBAction 应如下所示:
@IBAction func savePhotoTapped(_ sender: Any) {
print("in savePhotoTapped | start"
exportLivePhoto()
}
确保此操作已连接到您在情节提要中创建的按钮。
问题 2:多次保存:
这些行看起来像是保存了图像的 jpg 和 mov 版本。如果您只想要一个注释掉另一个。
try FileManager.default.removeItem(atPath: output + "/IMG.JPG")
try FileManager.default.removeItem(atPath: output + "/IMG.MOV")
还可以尝试清理您的代码,以便将来更容易阅读。
推荐阅读
- python - 在遍历行时获取 KeyError:61
- python - Python中的图形集成
- java - 向左或向右滑动以更改 Fragment 内的 RecyclerView
- reactjs - react-router-dom - 链接和history.push之间的区别?
- javascript - 如何知道chartjs中点击区域的索引?
- c - ***检测到堆栈粉碎***:
终止中止(核心转储) - c# - LINQ 表达式中的步入和步出
- javascript - 承诺数组两种不同的行为
- javascript - activiti 动态发送事务处理到特定的候选组
- python - 无法使用 python 和 Selenium webdriver 获取 javascript 生成的 html