How to detect when user used Password AutoFill on a UITextField

前端 未结 7 2158
半阙折子戏
半阙折子戏 2020-12-10 03:26

I\'ve implemented all the app and server changes necessary to support Password Autofill on iOS 11, and it works well. I\'d like it to work a little better.

My usern

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 04:01

    Not sure if the previous answer stopped working at some point, but I can't get it to work—I only get a single didBeginEditing call when AutoFill is used.

    However, I did find a way to detect AutoFill. And keep in mind that it is possible for AutoFill to be used after some characters have already been entered, for example if the user has already typed some numbers in the phone number, then they AutoFill the full number.

    For Swift 4/5:

    private var fieldPossibleAutofillReplacementAt: Date?
    
    private var fieldPossibleAutofillReplacementRange: NSRange?
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // To detect AutoFill, look for two quick replacements. The first replaces a range with a single space
        // (or blank string starting with iOS 13.4).
        // The next replaces the same range with the autofilled content.
        if string == " " || string == "" {
            self.fieldPossibleAutofillReplacementRange = range
            self.fieldPossibleAutofillReplacementAt = Date()
        } else {
            if fieldPossibleAutofillReplacementRange == range, let replacedAt = self.fieldPossibleAutofillReplacementAt, Date().timeIntervalSince(replacedAt) < 0.1 {
                DispatchQueue.main.async {
                    // Whatever you use to move forward.
                    self.moveForward()
                }
            }
            self.fieldPossibleAutofillReplacementRange = nil
            self.fieldPossibleAutofillReplacementAt = nil
        }
    
        return true
    }
    

提交回复
热议问题