在物联网计划上工作,但仍然深入人心,该程序现在应该做的只是在用户使用Touch ID成功验证时显示一条消息。并且每次用户打开程序时都应该这样做,无论它是第一次启动还是在后台运行后变为活动状态。
程序运行,但当它到达试图设置跟踪身份验证状态的静态布尔属性的块时,它会给我这个错误:
以下是完整代码:
AppDelegate.swift:
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
print("Launching...")
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
print("Exiting...")
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
ViewController.userIsAuthenticated = false
print("Exited")
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
print("Opening...")
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
print("Opened")
let viewInstance = ViewController()
viewInstance.authenticateUser()
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
print("Terminating!")
}
}
ViewController.swift:
import UIKit
import LocalAuthentication
@IBDesignable class ViewController: UIViewController {
//MARK: Properties
static var userIsAuthenticated: Bool{
get{
return false
}
set{
userIsAuthenticated = newValue
let alert = UIAlertController(title: "", message: "Authentication Successful!", preferredStyle: .actionSheet)
let viewInstance = ViewController()
viewInstance.present(alert, animated: true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.init(red: 0.3, green: 0.48, blue: 0.78, alpha: 1.0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func authenticateUser(){
if ViewController.userIsAuthenticated != true {
let authenticateUser = LAContext()
var authenticationError: NSError? = nil
let authenticationReason = "Authentication is needed to access your house!"
if authenticateUser.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &authenticationError){
authenticateUser.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason: authenticationReason, reply: {(success, error) in
if(success){
ViewController.userIsAuthenticated = true
}else{
print(error!.localizedDescription)
}
})
}else{
print("Authentication Error!", authenticationError!)
}
}
}
func displayAnAlert(title:String?, message: String?) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in
print("Cancel")
})
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in
print("OK")
})
self.present(alert, animated: true)
}
}
这是新代码:
AppDelegate.swift:
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
print("Launching...")
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
print("Exiting...")
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
ViewController.userIsAuthenticated = false
print("Exited")
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
print("Opening...")
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
print("Opened")
let viewInstance = ViewController()
viewInstance.authenticateUser()
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
print("Terminating!")
}
}
ViewController.swift:
import UIKit
import LocalAuthentication
@IBDesignable class ViewController: UIViewController {
//MARK: Properties
static var userIsAuthenticated: Bool!{
didSet{
let alert = UIAlertController(title: "", message: "Authentication Successful!", preferredStyle: .actionSheet)
let viewInstance = ViewController()
viewInstance.present(alert, animated: true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.init(red: 0.3, green: 0.48, blue: 0.78, alpha: 1.0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func authenticateUser(){
if ViewController.userIsAuthenticated != true {
let authenticateUser = LAContext()
var authenticationError: NSError? = nil
let authenticationReason = "Authentication is needed to access your house!"
if authenticateUser.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &authenticationError){
authenticateUser.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason: authenticationReason, reply: {(success, error) in
if(success){
ViewController.userIsAuthenticated = true
}else{
print(error!.localizedDescription)
}
})
}else{
print("Authentication Error!", authenticationError!)
}
}
}
func displayAnAlert(title:String?, message: String?) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in
print("Cancel")
})
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in
print("OK")
})
self.present(alert, animated: true)
}
}
答案 0 :(得分:0)
自从我对您的问题发表评论后,您已使用新错误编辑了该问题,表明您试图在不在窗口层次结构中的视图上显示警报。这是因为您刚刚创建了一个全新的视图:
let viewInstance = ViewController()
与任何窗口无关......因此错误。
据推测,您根本不想要一个新视图,但可能您已经拥有的视图正在执行authenticateUser()
。如果userIsAuthenticated
是一个实例属性,那么该视图只能作为self
使用,但您的属性为static
,因此情况并非如此。
如果没有为您重新设计解决方案,您的问题就没有简单的答案,这是您需要做的事情!是时候退后一步思考了。问问自己为什么你的财产是static
,为什么你试图从财产制定者发出警报等。
HTH