首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实时照片自动保存

实时照片自动保存
EN

Stack Overflow用户
提问于 2019-02-10 15:16:31
回答 1查看 146关注 0票数 0

Xcode新手,正在尝试制作一个应用程序来下载实时墙纸。我使用github的LivePhotoDemo编写了所有的代码。我的问题是,当页面加载时,它会显示实时照片,但在我的相片库中保存了两个副本,而我似乎想不出如何获得一个保存按钮来代替它(并且只有一个副本)

代码语言:javascript
复制
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。几年前,除了一些超文本标记语言和C++之外,我对编码几乎一无所知。我只知道如何查看代码,并试图理解每件事。有人能告诉我我哪里做错了吗?非常感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-11 16:36:29

这里有几件事可以让你摆脱困境。

问题1:如何让保存按钮调用exportLivePhoto():

您的按钮的IBAction应如下所示:

代码语言:javascript
复制
  @IBAction func savePhotoTapped(_ sender: Any) {
    print("in savePhotoTapped | start"
    exportLivePhoto()
  }

确保此操作已连接到您在情节提要中创建的按钮。

问题2:多个保存:

这些行看起来像是保存了图像的jpg和mov版本。如果你只想要一个注释而不是另一个。

代码语言:javascript
复制
try FileManager.default.removeItem(atPath: output + "/IMG.JPG")
try FileManager.default.removeItem(atPath: output + "/IMG.MOV")

也可以试着清理你的代码,以便将来更容易阅读。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54614236

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档