仿ios支付宝解锁功能(一)

本文介绍如何使用Swift在iOS应用中实现指纹解锁功能。利用LocalAuthentication框架进行指纹验证,并结合NSUserDefaults进行状态存储。代码示例展示了从设置指纹开关到实际解锁过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

指纹解锁

创建项目,Fingerlock,使用xcode7.3,开发语言swift。

创建一个运行如下的项目,运行如下:


在thirditem的界面添加安全设置按钮,点击进入安全设置列表,如图:

  

现在分析指纹解锁:

指纹解锁机制: 调用手机端录入指纹,使用home键验证用户指纹是否正确

代码:

import LocalAuthentication
  
        let context = LAContext()
        if #available(iOS 9.0, *) {
            context.evaluatePolicy(LAPolicy.DeviceOwnerAuthentication, localizedReason: "通过Home键验证已有手机指纹") { (sucess, authentcationError) in
                
                if sucess == true {
                    //解锁成功
                }else {
                    //解锁失败
                  
                }
            }
        } else {
            print("failed")
            // Fallback on earlier versions
        }
判断手机是否支持指纹解锁:
 let ctx = LAContext()
        if ctx.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: nil) == false{
            //手机不支持指纹解锁
        }
需要指纹解锁,还需用到数据存储,我这里简单使用NSUserDefaults来处理数据,代码:

建立Userinfo的类:

//设置指纹解锁
    func setLockWithFingerPrintOn(isOn: Bool) -> Bool {
        let userDefaults = NSUserDefaults.standardUserDefaults()
        let device : String = UIDevice.currentDevice().systemVersion
        let dou:Double = (device as NSString).doubleValue
        var newIsOn = isOn
        if dou <= 8 {
            newIsOn = false
        }
        let ctx = LAContext()
        if ctx.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: nil) == false{
            newIsOn = false
        }
        userDefaults.setBool(newIsOn, forKey: "fingerPrint")
        userDefaults.synchronize()
        return newIsOn
    }
    //读取指纹是否解锁
    func isLockWithfingerPrint() -> Bool {
        
        let device : String = UIDevice.currentDevice().systemVersion
        let dou:Double = (device as NSString).doubleValue
        if dou <= 8 {
            return false
        }
        let ctx = LAContext()
        if ctx.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: nil) == false{
            
            return false
        }
        let userDefaults = NSUserDefaults.standardUserDefaults()
        if userDefaults.objectForKey("fingerPrint") == nil {
            userDefaults.setBool(false, forKey: "fingerPrint")
            userDefaults.synchronize()
            return false
        }else{
            //开启指纹解锁功能
            return userDefaults.boolForKey("fingerPrint")
        }
    }
在Fingersettingcell的代码:
import UIKit

class FingersettingCell: UITableViewCell {

    typealias SwitchChose = (UISwitch) -> ()
    
    var choseclickwithswitch : SwitchChose?
    
    
    @IBOutlet weak var title: UILabel!
    @IBOutlet weak var issetting: UISwitch!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    func cellForModel(model : FingersettingModel) -> () {
        title.text = model.title
        issetting.on = model.isok
    }

    @IBAction func clickchose(sender: UISwitch) {
        if choseclickwithswitch != nil {
            choseclickwithswitch!(sender)
        }
    }
    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
}

在FingersettingController的代码:

import UIKit
import LocalAuthentication
class FingersettingController: UITableViewController {

    let dataarray : [FingersettingModel] = {
        let m1 =  FingersettingModel.init(dict: [:])
        m1.title = "指纹解锁"
        m1.isok = UserInfo.isLockWithfingerPrint()
        let m2 = FingersettingModel.init(dict: [:])
        m2.title = "支付解锁"
        return [m1,m2]
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        self.tableView.registerNib(UINib.init(nibName: "FingersettingCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "FingersettingCellID")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataarray.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("FingersettingCellID", forIndexPath: indexPath) as! FingersettingCell
        switch indexPath.row {
        case 0:
            cell.choseclickwithswitch = { swit in
                let isOn = UserInfo.setLockWithFingerPrintOn(swit.on)
                swit.on = isOn
                //不支持指纹解锁
                if swit.on == true && isOn == false {
                    print("手机不支持指纹功能或是您未设置指纹")
                    return
                }
                //当手势解锁是开启状态时
                if swit.on {
                //开启验证解锁 添加验证解锁代码
                    let context = LAContext()
                    //        var msg = ""
                    if #available(iOS 9.0, *) {
                        context.evaluatePolicy(LAPolicy.DeviceOwnerAuthentication, localizedReason: "通过Home键验证已有手机指纹") { (sucess, authentcationError) in
                            
                            if sucess == true {
                                UserInfo.setLockWithFingerPrintOn(true)

                            }else {
                                UserInfo.setLockWithFingerPrintOn(false)
                            }
                        }
                    } else {
                        UserInfo.setLockWithFingerPrintOn(false)
                    }

                }
                
            }
            break
        case 1:
            break
        default:
            break
        }
        cell.cellForModel(dataarray[indexPath.row])
        return cell
    }

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值