iOS Swift Tutorial: Basic Custom Camera App - AVFoundation

Поділитися
Вставка
  • Опубліковано 26 жов 2024

КОМЕНТАРІ • 62

  • @Daniel-sz2lq
    @Daniel-sz2lq 7 років тому +30

    Such a shame that AVFoundation is so complex. Great tutorial, Brian!

  • @stevep7950
    @stevep7950 6 років тому +2

    I'm running XCode 9.4.1 and I just had to make a few tweaks to get this working in the latest version but it works just as good as in the tutorial above. I changed the name of the class to brian in tribute to the maestro.

  • @cyberwarlus2758
    @cyberwarlus2758 3 роки тому +5

    8:44 where AVCaptureSessionPhoto in new version of Swift writes AVCaptureSession.Preset.photo

  • @VideoRamin
    @VideoRamin 3 роки тому +1

    Brian, I am doing this using Xcode 12.4 and it is impossible to follow. There are so many updates/changes. Do you have an updated video or have any suggestions?? THANKS

  • @jamesnoble8076
    @jamesnoble8076 7 років тому +3

    your voice is so relaxing, you should do asmr instead of programming vids lmao

  • @Someuserinthewest
    @Someuserinthewest 7 років тому

    Thanks Brian! Your vids are awesome!

  • @bradchen9317
    @bradchen9317 3 роки тому +4

    On where it says : "if let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)" it has an error saying "Initializer for conditional binding must have Optional type, not 'AVCaptureVideoPreviewLayer'". I'm not sure how to fix it, could you help? Thanks!

    • @zackchen6280
      @zackchen6280 2 роки тому

      Just googled it (in case someone is here in 2022):
      It means that you can just delete the if statement like:
      let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
      //... code from if statment here

  • @stevep7950
    @stevep7950 6 років тому +6

    Here is my updated Code :-)import UIKit
    import AVFoundation@available(iOS 10.0, *)
    class brian: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
    let captureSession = AVCaptureSession()
    var previewLayer:CALayer! //! means we can initialise this later
    var captureDevice:AVCaptureDevice!
    var takePhoto = false override func viewDidLoad() {
    super.viewDidLoad()
    }
    override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    prepareCamera()
    }
    func prepareCamera() {
    captureSession.sessionPreset = AVCaptureSession.Preset.photo
    let availableDevices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices
    captureDevice = availableDevices.first
    beginSession()
    }
    func beginSession() {
    do {
    let captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)
    captureSession.addInput(captureDeviceInput)
    } catch {
    print(error.localizedDescription)
    }
    let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    self.previewLayer = previewLayer
    self.view.layer.addSublayer(self.previewLayer)
    self.previewLayer.frame = self.view.layer.frame
    captureSession.startRunning()
    let dataOutput = AVCaptureVideoDataOutput()
    dataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString):NSNumber(value:kCVPixelFormatType_32BGRA)] as [String : Any]
    dataOutput.alwaysDiscardsLateVideoFrames = true
    if captureSession.canAddOutput(dataOutput) {
    captureSession.addOutput(dataOutput)
    }
    captureSession.commitConfiguration()
    let queue = DispatchQueue(label: "clockworksciencce")
    dataOutput.setSampleBufferDelegate(self, queue: queue)

    } //end beginSession() @IBAction func takePhoto(_ sender: Any) {
    takePhoto = true
    }
    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
    if takePhoto {
    takePhoto = false
    if let image = self.getImageFromSampleBuffer(buffer: sampleBuffer) {
    let photoVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PhotoVC") as! PhotoViewController
    photoVC.takenPhoto = image
    DispatchQueue.main.async {
    self.present(photoVC, animated: true, completion: {
    self.stopCaptureSession()
    })
    }
    }
    }
    } //end captureOutput()

    func getImageFromSampleBuffer(buffer:CMSampleBuffer) -> UIImage? //CM stands for Core Media
    {
    if let pixelBuffer = CMSampleBufferGetImageBuffer(buffer) {
    let ciImage = CIImage(cvPixelBuffer: pixelBuffer)
    let context = CIContext()
    let imageRect = CGRect(x: 0, y: 0, width: CVPixelBufferGetWidth(pixelBuffer), height: CVPixelBufferGetHeight(pixelBuffer))
    if let image = context.createCGImage(ciImage, from: imageRect) {
    return UIImage(cgImage: image, scale: UIScreen.main.scale, orientation: .right )
    }
    }
    return nil //if it doesn't work return a nil
    }
    func stopCaptureSession () {
    self.captureSession.stopRunning()
    if let inputs = captureSession.inputs as? [AVCaptureDeviceInput] {
    for input in inputs {
    self.captureSession.removeInput(input)
    }
    }
    }
    }

  • @dskurth
    @dskurth Місяць тому

    DOES THIS STILL WORK? I downloaded the tutorial files and an error comings up saying swift version not supported.

  • @henna._.0396
    @henna._.0396 Рік тому

    I am getting two error, i wish i could attach a screenshot but "Initializer for conditional binding must have Optional type, not 'AVCaptureVideoPreviewLayer'' and "Cannot convert value of type 'NSString' to expected dictionary key type 'String'" are the error. if you can help please.

  • @sergeirap33
    @sergeirap33 4 роки тому

    great, thankyou.

  • @jeffreyliang2345
    @jeffreyliang2345 2 роки тому

    Hi I am running this on a simulator, do you know why the code is fine but there is no live feed that shows up?

  • @wensmusic8636
    @wensmusic8636 2 роки тому

    hi, is it possible to do an updated 2021 version of this ?

  • @marcb396
    @marcb396 7 років тому

    That is pretty awesome! Thanks

  • @justingeeslin
    @justingeeslin 6 років тому

    Thanks Brian!

  • @dojun849
    @dojun849 4 роки тому

    awesome !

  • @TheSweeneyT
    @TheSweeneyT 7 років тому +5

    anyone knows which part of code i should change to have a video camera recorder?

  • @dowiee2694
    @dowiee2694 7 років тому

    Thanks, Brian!

  • @paulfox4636
    @paulfox4636 3 роки тому +1

    I'm trying to follow along with this vid, but swift is so different. It seems they have done away with storyboards and the UI elements are now hand coded...

  • @XKiTuX
    @XKiTuX 7 років тому

    Thanks alot brian 👍🏻

  • @paulmartinpatio9118
    @paulmartinpatio9118 6 років тому

    Good Day Sir such a wonderful tutorial. May I ask sir can i add a custom frame border in the image before saving. Thanks for reply :D

  • @botlin1
    @botlin1 4 роки тому

    Got this working with the help of some comments below. But I thought the image would save once taken? Or do I need a save button added to the Photo View Controller page?

    • @yuanx6256
      @yuanx6256 4 роки тому

      Hello! I tried to follow the tutorial. The app works well when taking the photo. But when I clicked "back" button to go back to ViewController page, it got stuck and showed the photo just taken. Any thoughts on why this happened? Thanks!

  • @وليدالنادي-ح3ق
    @وليدالنادي-ح3ق 5 років тому

    thank you :)

  • @daenou
    @daenou 7 років тому

    Hi Brian, great explanations, thanks! I would like to use the camera also in landscapeviews. How I supposed to it? Thanks für your answer.

    • @BrianAdvent
      @BrianAdvent  7 років тому +1

      Thanks Dea! Autolayout only works with views so you would need to adjust layer.frame in the viewWillTransition(to:with:) ViewController delegate method.

    • @developer3938
      @developer3938 7 років тому

      Thanks Brian! Awesome stuff...just learning app dev and swift...I figured out what what to do in viewWillTransition...
      self.previewLayer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
      I'm having trouble figuring out how to change the video orientation though?
      I know we would set it as previewLayer.connection.videoOrientation =
      The problem is we assigned previewLayer to the global previewLayer of type CALayer...so I don't know how to access the original AVCaptureVideoPreviewLayer
      I know its something simple, i'm just lost

    • @jiepan7281
      @jiepan7281 3 роки тому +1

      @@developer3938 this worked for me:
      override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
      super.viewWillTransition(to: size, with: coordinator)
      if let connection = self.previewLayer?.connection {
      let currentDevice: UIDevice = UIDevice.current
      let orientation: UIDeviceOrientation = currentDevice.orientation
      let previewLayerConnection : AVCaptureConnection = connection
      if (previewLayerConnection.isVideoOrientationSupported) {
      let videoOrientation = AVCaptureVideoOrientation(rawValue: orientation.rawValue)
      self.previewLayer?.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
      previewLayerConnection.videoOrientation = videoOrientation!
      }
      }
      }

  • @kentofujihara345
    @kentofujihara345 3 роки тому

    We are stuck in a problem that our camera app can't zoom in or out. Does anybody have any advice to solve this problem? That'll be very helpful

  • @Daniel-jn2mn
    @Daniel-jn2mn 6 років тому +2

    i tried getting through the whole thing but all along the way xcode compiler just kept screaming at me. Not sure if this video even works anymore to be honest

    • @martinadolfsson337
      @martinadolfsson337 6 років тому

      I have the same issue. Seems like the code is not compatible with Xcode 9.4 +

  • @mohamethseck
    @mohamethseck 7 років тому +7

    What about recording video

  • @olami7557
    @olami7557 7 років тому

    Hi brian, I tried accessing photos from photo library with a button but I get error. How can I use photo library with avfoundation

  • @bgtproductions9904
    @bgtproductions9904 7 років тому

    How could I make the camera viewing on a UIView? I'm tinkering with writing imageView.layer.addSublayer(self.previewLayer) but that doesn't seem to be enough. Any suggestions? (imageView is a UIView)

  • @ikennaudokporo6061
    @ikennaudokporo6061 4 роки тому

    no sound when photo is captured.

  • @shivamkhandelwal1396
    @shivamkhandelwal1396 7 років тому

    An AVCaptureInput instance may not be added to more than one session . getting an error....help me to resolve?

  • @maliyapalanikumar8047
    @maliyapalanikumar8047 4 роки тому

    I am using Xcode 11.3.1 I did the same as shown in video,My app is getting crash.please,anyone help me to resolve

  • @mex5341
    @mex5341 4 роки тому

    how to add live filter preview on a camera ?

  • @prosyarceno6607
    @prosyarceno6607 4 роки тому

    hello! After following your tutorial with a few minor changes, which would not do anything drastic I suppose, for Swift 5 and Xcode 11 my output image on the next view controller is rotated 90 degrees to the right. Was there an update on the OS or something? Really hope you can see this even after 3 years. haha

    • @yuanx6256
      @yuanx6256 4 роки тому

      Hello! I tried to follow the tutorial. The app works well when taking the photo. But when I clicked "back" button to go back to ViewController page, it got stuck and showed the photo just taken. Any thoughts on why this happened? Thanks!

  • @tomernakash1025
    @tomernakash1025 7 років тому

    How do I program a camera app that will take a photo with auto focus and right after that it will take a photo with the shortest focal length the phone can capture??

  • @Amqzong
    @Amqzong 7 років тому

    Using this tutorial, I was able to program an app that takes a picture and shows it to me in Photo View Controller. However, when I click the "go back" button and it brings me back to the View Controller screen, the video feed is frozen and I'm unable to take another picture. How can I fix this? Thanks!

    • @Amqzong
      @Amqzong 7 років тому

      Never mind, fixed it. Under the captureOutput block in View Controller, I accidentally put self.present(photoVC, animated: true, completion: self.stopCaptureSession) instead of self.present(photoVC, animated: true, completion: nil)

  • @kevstuckbykevdotcom2743
    @kevstuckbykevdotcom2743 7 років тому

    hi brian great videos. i have a question, I have used this video's code in my iPad app but it comes to a slow crawl when the view Controller loads the camera. It takes at lease 30 seconds for the view controller to finally animate in. (Also, I'm testing this in simulator and not on a real device) any thoughts??

  • @bhautikziniya246
    @bhautikziniya246 7 років тому

    Hi Brian i want to capture a square video using sample buffer line insta can you guid how can i achive square video.

    • @ravvvioli
      @ravvvioli 7 років тому

      mmm, dont u just make the view square? like the view thing u put in first, make that a square?

  • @swisstipidesigner6292
    @swisstipidesigner6292 7 років тому +2

    God this is confusing... You completely lost me when you started setting up the dataOuput. But other than that great tutorial!

  • @PositiverHeld1
    @PositiverHeld1 6 років тому +2

    Hi Brian, thanks for the great video. Unfortunately I get the following error message, regrettably I don't get it fixed. Can you or someone else here give me a tip. Thank you
    Error: Initializer for conditional binding must have Optional type, not '[AVCaptureDevice]'
    in the if statement " if let availableDevices = AVCaptureDevice.DiscoverySession(deviceTypes:[.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices
    { ...." in ViewController.swift

    • @EthanPetersFilms
      @EthanPetersFilms 5 років тому +1

      Same!

    • @mohammadagustiar9833
      @mohammadagustiar9833 5 років тому

      me too

    • @marvingbh
      @marvingbh 5 років тому +2

      Remove the if let, should be like that:
      let availableDevices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices
      captureDevice = availableDevices.first
      beginSession()

  • @s11gangsta
    @s11gangsta 7 років тому

    mine comes up with "terminating with uncaught exception of type NSException"

  • @denis1376
    @denis1376 2 роки тому

    Anyone can add one function to this app?

  • @Anonymous-vh6kp
    @Anonymous-vh6kp 6 років тому

    my capture output delegate function never gets called

    • @uVeVentrue
      @uVeVentrue 4 роки тому

      Check parameters ! it’s different now in Xcode 11

  • @Bayareabob
    @Bayareabob 7 років тому

    what is your accent?

    • @wolfzwiful
      @wolfzwiful 4 роки тому

      Sounds like a mix between West Coast of United States, Chinese, and German.