-1

I am trying to rewrite the AVCam example from Apple in Swift. When I check if the device is authorized I want to set the property deviceAuthorized to true or false.

I get inside the block because I get "Access is granted" in my output. But when I want to check if my property is changed it still says it is false. I also tried with a local variable but this isn't working either.

What am I doing wrong?

var deviceAuthorized:Bool?

...

func checkDeviceAuthorizationStatus() -> Bool{
    var mediaType = AVMediaTypeVideo
    var localDeviceAuthorized:Bool = false

    AVCaptureDevice.requestAccessForMediaType(mediaType, completionHandler: {
        (granted:Bool) -> () in
        if(granted){
            println("Access is granted")
            self.deviceAuthorized = true
            localDeviceAuthorized = true
        }else{
            println("Access is not granted")

        }
    })

    println("Acces is \(localDeviceAuthorized)")
    return self.deviceAuthorized!
}

2 Answers2

0

You're trying to return self.deviceAuthorized!, but the completion handler won't have run by that point. If you're trying to check the value of the property by looking at the return value of this function, it will be the value of the variable before the completion handler ran.

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • Thanks! it was indeed because I returned before the completion handler had run. I thought this would be completed immediately. – Thomas Heylen Jun 21 '14 at 22:02
0

try writing your completion block like this:

AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: {
    granted in      // no need to specify the type, it is inferred from the completion block's signature
    if granted {    // the if condition does not require parens
        println("Access is granted")
        self.deviceAuthorized = true
    } else {
        println("no access")
    }
    self.displayAuth()
    })

...and then add an instance method displayAuth()

func displayAuth() {
    println("Access is \(deviceAuthorized)")
}

This will help you see that the property has indeed been set from within the block; the new method that I added here displayAuth, we are calling from within the block after your conditional sets the value of deviceAuthorized - the other attempts you were making to check the value of the property were occurring before the requestAccessForMediaType method had a chance to complete and call its completion block, so you were seeing the value reported before the completion block had a chance to set it... this way you will be able to see the value after the block has had a chance to do its thing.

fqdn
  • 2,823
  • 1
  • 13
  • 16