Сохранение видео с помощью UIImagePickerController для приложения Dashcam - PullRequest
0 голосов
/ 03 мая 2019

Я пытаюсь получить всплывающее предупреждение для сохранения видео из триггера из CoreMotion Данные.

У меня проблемы с сохранением видео из запроса Да.

let imagePicker = UIImagePickerController()

       imagePicker.allowsEditing = true
       imagePicker.delegate = self
       imagePicker.sourceType = .camera;
       imagePicker.mediaTypes = [kUTTypeMovie as String]
       imagePicker.allowsEditing = false
       imagePicker.showsCameraControls = false
            imagePicker.perform(#selector(UIImagePickerController.startVideoCapture), with: nil, afterDelay: 1)

            // shows camera onto screen
       self.present(imagePicker, animated: true)     
            do {
            motion.accelerometerUpdateInterval = 0.25
            motion.startAccelerometerUpdates(to: OperationQueue.current!) { (data, error) in
                print(data as Any)
                if let trueData = data {
                    //self.view.reloadInputViews()
                    let x = trueData.acceleration.x
                    let y = trueData.acceleration.y
                    let z = trueData.acceleration.z
                    let totalAcceleration = calculateMagnitude (no1:Float (x), no2: Float (y),no3: Float (z))

                    if (Float(totalAcceleration) > 2.00){


                        self.dismiss(animated: true, completion : nil)
                        let alert = UIAlertController (title: "Sudden acceleration detected", message: "Are you in an accident?", preferredStyle: .alert)
                        self.present(alert, animated: true, completion: nil)
                        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: {(action:UIAlertAction!) in
                            print("User has selected Yes")//Here is where I want to save the video
                        }))

                        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: {(action:UIAlertAction!) in
                            print("User has selected No")
                            imagePicker.perform(#selector(UIImagePickerController.startVideoCapture), with: nil, afterDelay: 1)
                            // shows camera onto screen
                            self.present(imagePicker, animated: true)
                        }))
                    }

Все ответы, которые я нашел, на самом деле мне совсем не помогли: [

TLDR: Запустить приложение.Телефон записывает, что перед ним.Изменение в CoreMotion данных.Да или Нет Подсказка появляется.Нет продолжает запись.Да сохраняет видео.

1 Ответ

0 голосов
/ 03 мая 2019

Не забудьте нажать на экран, чтобы начать захват

import UIKit
import Photos
import MobileCoreServices
import CoreMotion

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    lazy var imagePicker: UIImagePickerController = {
        let ip = UIImagePickerController()
        ip.delegate = self
        ip.sourceType = .camera
        ip.mediaTypes = [kUTTypeMovie as String]
        ip.allowsEditing = false
        ip.showsCameraControls = false
        return ip
    }()

    let motion: CMMotionManager = {
        let motion = CMMotionManager()
        motion.accelerometerUpdateInterval = 0.25
        return motion
    }()

    var videoUrl: URL?

    override func viewDidLoad() {
        super.viewDidLoad()

        // First Check for photo library permission
        checkPhotoLibraryPermission()
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        startCapture()
    }

    func checkPhotoLibraryPermission() {
        let status = PHPhotoLibrary.authorizationStatus()
        switch status {
        case .authorized:
        //handle authorized status
            break
        case .denied, .restricted :
        //handle denied status
            break
        case .notDetermined:
            // ask for permissions
            PHPhotoLibrary.requestAuthorization { status in
                switch status {
                case .authorized:
                // as above
                    break
                case .denied, .restricted:
                // as above
                    break
                case .notDetermined:
                    // won't happen but still
                    break
                }
            }
        }
    }

    func startCapture() {
        self.present(imagePicker, animated: true) {
            self.imagePicker.perform(#selector(self.imagePicker.startVideoCapture), with: nil, afterDelay: 1)
        }

        motion.startAccelerometerUpdates(to: .main) { (data, error) in
            if let error = error {
                print(error)
                return
            }

            guard let data = data else { return }
            let x = data.acceleration.x
            let y = data.acceleration.y
            let z = data.acceleration.z

            let totalAcceleration = sqrt(x*x + y*y + z*z)
            if totalAcceleration > 2 {
                self.imagePicker.stopVideoCapture()
                self.imagePicker.dismiss(animated: true, completion: nil)
                self.showAlert()
            }
        }
    }

    func showAlert() {
        let alert = UIAlertController (title: "Sudden acceleration detected", message: "Are you in an accident?", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: {(action:UIAlertAction!) in
            print("User has selected Yes") // Here is where I want to save the video

            if let videoUrl = self.videoUrl {
                self.saveVideoToPhotos(videoUrl)
            }

        }))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: {(action:UIAlertAction!) in
            print("User has selected No")
            self.present(self.imagePicker, animated: true) {
                self.imagePicker.perform(#selector(self.imagePicker.startVideoCapture), with: nil, afterDelay: 1)
            }
        }))
        self.present(alert, animated: true, completion: nil)
    }

    func saveVideoToPhotos(_ videoUrl: URL) {
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoUrl)
        }) { saved, error in
            if saved {
                let alertController = UIAlertController(title: "Your video was successfully saved", message: nil, preferredStyle: .alert)
                let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                alertController.addAction(defaultAction)
                self.present(alertController, animated: true, completion: nil)
            }
        }
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let videoUrl = info[.mediaURL] as? URL {
            self.videoUrl = videoUrl
        }
    }
}
...