Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.
Make OTP view on iOS
Almost every app now uses a phone number for Login/ SignUp. So now you want to add OTP verification to your app. And it seems pretty easy, right?
Just add 5 UITextFields, Add handlers, Manage next responders, Manage backspace/ delete button, Manage color change, Show keyboard, Hide keyboard, Concat all strings. After all, this change design to match your app appearance Underlined, diamond, rounded, circle and then show or hide code.
That’s Simple, no?
Okay, don’t worry I’ll make it simple. There’s a pod that’ll make all this go away and handles everything itself. All you have to do is make a view and fetch OTP string. That’s It.
1. Create a new Xcode project. File > New > Project
2. Choose a name, choose team, change the language to Swift and User Interface to Storyboard and complete initializing project
3. Add CocoaPods. CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. It lets you install Libraries, also known as Pods, in your project
‘sudo gem install cocoapods’
You must use sudo to install CocoaPods, but you won’t need to use sudo after it’s installed.
4. Run commands ‘pod init’ and then ‘pod install’
Pod init will create a Podfile for your project and Pod install will install pod in your project.
5. After Pod install, Open Finder and you’ll see a new file ProjectName.xcworkspace. Now close .xcodeproj file and open .xcworkspace file.
6. In Project, Open Podfile , Pods > podfile and add this pod OTPFieldView
7. Under # Pods for ProjectName add Pod ‘OTPFieldView’
8. And run, ‘pod Update’. Pod update will command cocapods to install/refresh all listed pods in your podfile
9. Now you’ve successfully installed OTPFieldView.
10. Now to make OTP view. Drag and Add UIView and change its class and module to OTPTextField. Also, add it’s height and width constraints.
11. In ViewController, import OTPFieldView and add link the UI element to ViewController.
12. Add the following code to customize the field, you can customize it to your need. Check here
13. Finally, add delegate and Delegate methods
hasEnteredAllOTP(): Returns true when all text Fields are full.
shouldBecomeFirstResponderForOTP(): Show keyboard automatically.
enteredOTP(): Get entered pin.
And your view is ready. Now you can easily do phone validation using OTP.
Did you like what you read? Let me know your thoughts in the comments!
People are also reading:
Leave a comment
How to clear the OTP fields and how to make autofill with the OTP received.
How to reset or clear the OTP fields, programmatically.
How to change text color its showing black
How to set OTP in this fields?