Ios 更改完成块内特性的值
我试图在Swift中重写苹果的AVCam示例。 当我检查设备是否已授权时,我希望将属性deviceAuthorized设置为true或false 我进入该块是因为我在输出中获得了“已授予访问权限”。 但是,当我想检查我的财产是否发生了变化时,它仍然说这是错误的。 我也尝试过使用局部变量,但这也不起作用 我做错了什么Ios 更改完成块内特性的值,ios,properties,closures,swift,completionhandler,Ios,Properties,Closures,Swift,Completionhandler,我试图在Swift中重写苹果的AVCam示例。 当我检查设备是否已授权时,我希望将属性deviceAuthorized设置为true或false 我进入该块是因为我在输出中获得了“已授予访问权限”。 但是,当我想检查我的财产是否发生了变化时,它仍然说这是错误的。 我也尝试过使用局部变量,但这也不起作用 我做错了什么 var deviceAuthorized:Bool? ... func checkDeviceAuthorizationStatus() -> Bool{ var
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!
}
您正在尝试返回
self.deviceAuthorized代码>,但完成处理程序在该点之前不会运行。如果您试图通过查看此函数的返回值来检查属性的值,则它将是在完成处理程序运行之前的变量值。尝试这样编写完成块:
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()
})
…然后添加一个实例方法displayAuth()
这将帮助您看到属性确实是从块内设置的;我在这里添加的新方法displayAuth
,在您的条件设置了deviceAuthorized
的值之后,我们正在从块内调用-您检查属性值的其他尝试发生在requestAccessForMediaType
方法有机会完成并调用其完成块之前,因此,在完成块有机会设置之前,您看到报告的值。。。这样,在块有机会完成其工作后,您将能够看到值。谢谢!这确实是因为我在完成处理程序运行之前返回。我以为这会马上完成。
func displayAuth() {
println("Access is \(deviceAuthorized)")
}