我希望允许通过1.5秒的长按启动实时流,但我的代码要求用户按住整个流的按钮

时间:2017-02-20 18:52:01

标签: ios swift uigesturerecognizer

我需要允许用户通过按下额外的相机按钮约1.5秒来开始直播视频给他们的朋友。然而,目前他们必须在整个时间内保持它,并且当他们从additionalCameraButton移开他们的手指时,cameraView被取消。

我正在使用我刚从Swift 2.2转换到Swift 3的旧代码,我看到了他们做了什么,但是当我稍微修改它以获得longTap手势的minimumDuration时,我会遇到致命的错误。

你们怎么会改变代码以允许1.5秒longTap而不是无限期地保持它?在第58行,我有代码为longTap添加minimumDuration但添加它会导致各种错误,就像放开按钮一样,即使实时流已经开始,cameraView仍然会被取消。

import UIKit
import AVFoundation

protocol CameraViewDelegate {
func startStopRecordingVideo(_ isStart: Bool)
func startStopStream(_ isStart: Bool)
func cancelCameraView()
func changeCamera()
func chooseVideo()
}

class CameraView: UIView, UIGestureRecognizerDelegate {

@IBOutlet weak var flashBtn: UIButton!
@IBOutlet weak var screenView: UIView!
@IBOutlet weak var shootBtn: UIButton!
@IBOutlet weak var changeCameraBtn: UIButton!
@IBOutlet weak var cancelBtn: UIButton!
@IBOutlet weak var alphaView: UIView!
@IBOutlet weak var shootBtnContainerView: UIView!

var delegate : CameraViewDelegate?
var isRecording : Bool = false
var isStreaming: Bool = false

var circleLayer: CAShapeLayer?
var timer: Timer?

//MARK: SYSTEMS METHODS

class func instanceFromNib() -> CameraView {
    return UINib(nibName: "View", bundle: nil).instantiate(withOwner: nil,     options: nil)[0] as! CameraView
}

override func awakeFromNib() {
    layoutIfNeeded()
    shootBtnContainerView.layer.cornerRadius =     shootBtnContainerView.frame.size.width/2
    shootBtn.layer.cornerRadius = shootBtn.frame.size.width/2

    let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped))
    tap.numberOfTapsRequired = 2
    shootBtn.addGestureRecognizer(tap)

    let hideTap = UITapGestureRecognizer(target: self, action: #selector(hideTapped))
    hideTap.delegate = self
    alphaView.addGestureRecognizer(hideTap)

    let hold = UILongPressGestureRecognizer(target: self, action: #selector(longTap))
    shootBtn.addGestureRecognizer(hold)
    //hold.minimumPressDuration = 1.5

    if Defaults.sharedDefaults.userKnowAboutCamera {
        alphaView.isHidden = true
    }

    let alert = UIAlertController(title: "Testing!", message: nil, preferredStyle: .alert)
    let action = UIAlertAction(title: "Thank You", style: .default, handler: nil)
    alert.addAction(action)

}

//MARK: - CIRcLE ANIMATION

func createCirclePath() {
    let circlePath = UIBezierPath(arcCenter: shootBtnContainerView.center, radius: shootBtnContainerView.frame.size.width/2, startAngle: 0.0, endAngle: CGFloat(.pi * 2.0), clockwise: true)

    circleLayer = CAShapeLayer()
    circleLayer!.path = circlePath.cgPath
    circleLayer!.fillColor = UIColor.clear.cgColor
    circleLayer!.strokeColor = UIColor.red.cgColor
    circleLayer!.lineWidth = 3.0;

    circleLayer!.strokeEnd = 0.0

    layer.addSublayer(circleLayer!)
}

func animateCircle(_ duration: TimeInterval) {
    circleLayer?.removeFromSuperlayer()
    createCirclePath()
    circleLayer!.strokeEnd = 0.0
    let animation = CABasicAnimation(keyPath: "strokeEnd")
    animation.duration = duration
    animation.fromValue = 0
    animation.toValue = 1
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
    circleLayer!.strokeEnd = 1.0
    circleLayer!.add(animation, forKey: "animateCircle")
}


// SHOW HIDE ALPHA VIEW

func showHideAlphaView(_ isHide: Bool){
    Defaults.sharedDefaults.userKnowAboutCamera = true
    var alpha: Float = 0.0
    if isHide { alpha = 0.0 } else { alpha = 0.6 }

    UIView.animate(withDuration: 1.5, animations: {
        self.alphaView.alpha = CGFloat(alpha)
        }, completion: nil)
}

// ACTIONS

func hideTapped(){
    showHideAlphaView(true)
}

func doubleTapped() {
    delegate?.chooseVideo()
}

func longTap(_ sender: UILongPressGestureRecognizer) {
    print("tapping")
    if sender.state == .began {
        SSContact.shared.isStreaming(public: true, to: nil, verification: { (error) in
            if error != nil {
                print(error!.localizedDescription)
            }
        }, live: { (live, views) in
            print("Live: \(live) :: With \(views) Views!")
        })
        isRecording = !isRecording
        delegate?.startStopRecordingVideo(isRecording)
        isStreaming = !isStreaming
        delegate?.startStopStream(isStreaming)
    } else if sender.state == .ended {
        SSContact.shared.stopStreaming()
        isRecording = !isRecording
        delegate?.startStopRecordingVideo(isRecording)
        isStreaming = !isStreaming
        delegate?.startStopStream(isStreaming)
        delegate?.cancelCameraView()
    }
}

func updateTimer() {
    isRecording = !isRecording
    delegate?.startStopRecordingVideo(isRecording)
    timer?.invalidate()
}

@IBAction func shootVideo(_ sender: AnyObject) {
    if !isRecording{
        timer = Timer.scheduledTimer(timeInterval: 20.0, target: self, selector: #selector(CameraView.updateTimer), userInfo: nil, repeats: true)
        animateCircle(20)
    } else {
        timer?.invalidate()
        circleLayer?.removeAnimation(forKey: "animateCircle")
        circleLayer!.strokeEnd = 0.0
    }
    isRecording = !isRecording
    delegate?.startStopRecordingVideo(isRecording)
}

@IBAction func cancelPressed(_ sender: AnyObject) {
    delegate?.cancelCameraView()
}

@IBAction func changeCameraPressed(_ sender: AnyObject) {
    delegate?.changeCamera()
}

@IBAction func flashBtnPressed(_ sender: AnyObject) {
    let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)!
    if (device.hasTorch) {
        do {
            try device.lockForConfiguration()
            if device.torchMode == .on {
                device.torchMode = .off
                flashBtn.setImage(UIImage(named: "Flash"), for: UIControlState())
            } else {
                flashBtn.setImage(UIImage(named: "NoFlash"), for: UIControlState())
                do {
                    try device.setTorchModeOnWithLevel(1.0)
                } catch {
                    print(error.localizedDescription)
                }
            }
            device.unlockForConfiguration()
        } catch {
            print(error.localizedDescription)
        }
    }
}

@IBAction func loadVideoPressed(_ sender: AnyObject) {

}
}

2 个答案:

答案 0 :(得分:0)

您的UILongPressGestureRegonizer目标是longTap(_:)。只要手势识别器触发事件​​,就会执行此方法。让我们看一下这个方法的实现:

func longTap(_ sender: UILongPressGestureRecognizer) {
    print("tapping")
    if sender.state == .began {
        // ...
        delegate?.startStopStream(isStreaming)
    } else if sender.state == .ended {
        SSContact.shared.stopStreaming()
        // ...
    }
}

我用// ...替换了一些代码,专注于此处的重点。如您所见,UILongPressGestureReconizer可以有多个状态(另请参阅API Reference)。在您的代码中,您正在处理其中两个:.began.ended

一旦您的手势被识别(即用户已执行长按),手势识别器状态将为.began。在这个if分支中,您正在开始摄像机录制以及您的流。另一方面,在.ended分支中,您将停止流式传输。当手势结束时(即,当用户抬起手指时,当长按已经结束时),状态将为.ended

如果您希望在长按后继续播放流,只需删除.ended分支。

答案 1 :(得分:0)

查看longTap的{​​{1}}方法,您说UILongPressGestureRecognizer基本停止流式传输,因此每当用户释放触摸时,它都会停止:

if sender.state == .ended

我建议可能有一种方法可以根据您的func longTap(_ sender: UILongPressGestureRecognizer) { if sender.state == .began { // Start the stream } else if sender.state == .ended { SSContact.shared.stopStreaming() isRecording = !isRecording delegate?.startStopRecordingVideo(isRecording) isStreaming = !isStreaming delegate?.startStopStream(isStreaming) delegate?.cancelCameraView() } } 布尔值管理启动和停止流,并更改isRecording声明使用isRecording的方式:

didSet

现在您可以使用longPress识别器来启动和停止流式传输:

var isRecording: Bool = false {
    didSet{
        // Manage the stream based on how the variable is set
        self.manageStream(start: isRecording)
    }
}


func manageStream(start: Bool) {

    if start {
        // Start the stream
        SSContact.shared.isStreaming(public: true, to: nil, verification: { (error) in
            if error != nil {
                print(error!.localizedDescription)
            }
        }, live: { (live, views) in
            print("Live: \(live) :: With \(views) Views!")
        })
        isRecording = !isRecording
        delegate?.startStopRecordingVideo(isRecording)
        isStreaming = !isStreaming
        delegate?.startStopStream(isStreaming)
    }
    else {
        // Stop the stream
        SSContact.shared.stopStreaming()
        isRecording = !isRecording
        delegate?.startStopRecordingVideo(isRecording)
        isStreaming = !isStreaming
        delegate?.startStopStream(isStreaming)
        delegate?.cancelCameraView()
    }

}

您甚至可以更改印刷机的持续时间,例如您希望最小印刷持续时间远远少于关闭流而不是将其打开:

func longTap(_ sender: UILongPressGestureRecognizer) {

    isRecording = !isRecording

}