Get id of button from webview on tap in swift - ios

I have a webview in which I load a url coming from a backend server. There is a button in my webview on which when user tap I want to get the id of that button. How I can get the id of that button? I have used a tap gesture on which when I click I'm trying to get the id but it's not working, my code is this,
let webViewTapped = UITapGestureRecognizer(target: self, action: #selector(self.tapAction(_:)))
webViewTapped.numberOfTapsRequired = 1
webViewTapped.delegate = self
webView.addGestureRecognizer(webViewTapped)
#objc func tapAction(_ sender: UITapGestureRecognizer?) {
print("touched")
// Get the specific point that was touched
let point: CGPoint? = sender?.location(in: view)
webView.evaluateJavaScript("document.getElementById(\"hdfUserId\").value") {(response, error) in
if (response != nil) {
let title = response as! String
print(title)
}
// error handling
}
}
This is how I'm trying to get the button id by javascript, but I'm getting fail in that

Related

Alamofire service calls multiple times

Alamofire.request("https://example.com/writecomment.php", method: .post, parameters: parameters).validate().responseJSON { response in
switch response.result {
case .success:
if let json = response.result.value {
var success = 0
if let dictJSON = json as? [String: AnyObject] {
if let successInteger = dictJSON["success"] as? Int {
success = successInteger
if success == 1
{
//succes
}
}
}
}
case .failure(_):
return
}
}
This is connected to an UIButton action
It SOMETIMES triggers service calls multiple times when user tap button.
How to prevent multiple calls?
Example::
var isAPICalling = false
#IBAction func btnTapped(_ sender: UIButton) {
if isAPICalling == false
{
isAPICalling = true
self.APICalling() // Your API calling method
}
}
In APICalling() method set isAPICalling = false when you get response.
OTHER OPTION :
Use ActivityIndicator when you request that time start indicator and after response stop indicator. So you cannot able to tap on button.
You can do one thing without using flag, if you have button outlet then just make button state selected when button click action is performed.
then call API and once you get the response make button state normal. so it will call only once when user click on button.
#IBAction func btnApiAction(_ sender: Any) {
if btnAPI.isSelected == false {
btnAPI.isSelected = true
//Call API here
}else {
//Do nothing here
}
}
if API Call is get failed or if you are getting any error then also change button state to normal so user can click again on button.
Disable UIButton when you call API. And enable back when api call finished.
#IBAction func didTapButton(_ sender: UIButton) {
sender.isEnabled = false
Alamofire.request(/* Params */) { response in
sender.isEnabled = true
// parse response - response.result
}
}
I prefer to add ActivityIndicatorView to the button view, and remove when finished for better UX.

Call a phone number from a UILabel with UITapGestureRecognizer Swift

I want the user to be able to tap on a phone number and call it directly. I have 3 different numbers for each person (private, mobile and work) and 3 different labels for this.
Now if I tap on the first or second label nothing happens, and when I tap on the third label (work) it calls the action form the first label (private).
so my first question: What did I wrong that it doesnt recognize the sender I tapped?
second question: What do I have to write in the function didTapPhoneNumber as an if statement?
phoneNumberPrivate2.isUserInteractionEnabled = true
phoneNumberMobile2.isUserInteractionEnabled = true
phoneNumberWork2.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(self.didTapPhoneNumber(_:)))
tap.numberOfTapsRequired = 1
tap.numberOfTouchesRequired = 1
phoneNumberPrivate2.addGestureRecognizer(tap)
phoneNumberMobile2.addGestureRecognizer(tap)
phoneNumberWork2.addGestureRecognizer(tap)
}
//call me maybe
#objc func didTapPhoneNumber(_ sender: UITapGestureRecognizer) {
print("success")
let privateCall = phoneNumberPrivate2.text?.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
let mobileCall = phoneNumberMobile2.text?.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
let workCall = phoneNumberWork2.text?.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
if sender == phoneNumberPrivate2 {
print("you tapped label \(self.phoneNumberPrivate2)")
if let url = URL(string: "tel://\(String(describing: privateCall))") {
UIApplication.shared.openURL(url)
}
} else if sender == phoneNumberMobile2 {
print("you tapped label \(self.phoneNumberMobile2)")
if let url = URL(string: "tel://\(String(describing: mobileCall))") {
UIApplication.shared.openURL(url)
}
} else if sender == phoneNumberWork2 {
print("you tapped label \(self.phoneNumberWork2)")
if let url = URL(string: "tel://\(String(describing: workCall))") {
UIApplication.shared.openURL(url)
}
} else {
print("action failed")
}
}
First, a gesture recognizer can't be assigned to more than one view. If you attempt to do so, it will only work on the last view you add it to. You need to create a unique tap gesture for each label. They can each use the same selector.
Next, you are attempting to compare sender (which is the gesture) to each of the labels. That won't work. You need to compare sender.view to each of the labels.
Last, move privateCall, mobileCall, and workCall within each relevant if statement. No need to calculate all three when only one is relevant for a given tap.
Really last, do not use String(describing:) to build the URL. Properly unwrap the optional values as needed.

How to get user's phone number?

I have just started using Digits - Twitter API for Phone Number verification, but it seems I'm unable to read the user's Phone number, I'm not sure if there is a function for that or so, but after reading a while I knew that I can do that with a Call back after successful phone verification but no explanation for that !
AuthConfig.Builder authConfigBuilder = new AuthConfig.Builder()
.withAuthCallBack(callback)
.withPhoneNumber(phoneNumberOrCountryCodeFromMyActivity)
found this snippet but again not sure where to implement it.
HERE is my Action for the login button with phone verification:
fileprivate func navigateToMainAppScreen() {
performSegue(withIdentifier: "signedIn", sender: self)
}
#IBAction func tapped(_ sender: Any) {
let configuration = DGTAuthenticationConfiguration(accountFields: .defaultOptionMask)
configuration?.appearance = DGTAppearance()
configuration?.appearance.backgroundColor = UIColor.white
configuration?.appearance.accentColor = UIColor.red
// Start the Digits authentication flow with the custom appearance.
Digits.sharedInstance().authenticate(with: nil, configuration:configuration!) { (session, error) in
if session != nil {
// Navigate to the main app screen to select a theme.
self.navigateToMainAppScreen()
} else {
print("Error")
}
}
}
So I found the answer after digging a lot more in Digits Documentations and it was pretty simple, I had to add:
print(session.phoneNumber)
print(session.userID)
In the didTap function, so the complete code will be:
#IBAction func tapped(_ sender: Any) {
let configuration = DGTAuthenticationConfiguration(accountFields: .defaultOptionMask)
configuration?.appearance = DGTAppearance()
configuration?.appearance.backgroundColor = UIColor.white
configuration?.appearance.accentColor = UIColor.red
// Start the Digits authentication flow with the custom appearance.
Digits.sharedInstance().authenticate(with: nil, configuration:configuration!) { (session, error) in
if session != nil {
//Print Data
print(session?.phoneNumber)
print(session?.userID)
// Navigate to the main app screen to select a theme.
self.navigateToMainAppScreen()
} else {
print("Error")
}
}
}
Here is the Reference I have used:
https://docs.fabric.io/apple/examples/cannonball/index.html#sign-in-with-digits

UITapGestureRecognizer is not opening url

I have created an action when tapping an image to open an URL in navigator but when I tap on it, nothing opens up. This is my code:
#IBAction func Anuncio(sender: UITapGestureRecognizer) {
if let url = NSURL(string: "http://capturando.es/") {
UIApplication.sharedApplication().openURL(url)
}
}
check once yourImagename.userInteractionEnabled = true or false if it is false just enable once thereafter all other functions are automatically triggered
yourImagename.userInteractionEnabled = true

Call using an app when uibutton is clicked

I have an app that displays a telephone number, and that number is in a uibutton. When the button is clicked, I want it to call. What is the best way to do it?
Get the text from the button into an NSUrl and pass it in:
let url = NSURL(string: button.currentTitle)
UIApplication.sharedApplication().openURL(url)
If when your selector for the button is called it passes the button into the method. So you can just grab it from there.
func buttonTapped(sender: AnyObject) {
if let button : UIButton = sender as? UIButton {
if let url = NSURL(string: button.titleLabel?.text) {
UIApplication.sharedApplication().openURL(url)
}
}
}

Resources