UITapGestureRecognizer is not opening url - ios

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

Related

Get id of button from webview on tap in swift

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

Button in Today Widget Xcode

New here to Xcode and Swift. I am working on an IOT app that enables me to switch a light on at a distance through a button on my today extension.
So I activated app groups and I am using UserDefaults to share info between app and widget. My logic being when button is pressed on the widget it returns a bool true. And if it returns true, I activate for now what is a LED on my ESP8266.
However, this doesn't seem to work, when I click the button nothing happens. What am I doing wrong? Any help or hints would be great! Thank you.
In viewcontroller.swift
override func viewDidLoad() {
defaults?.synchronize()
let Distribute = defaults?.bool(forKey: "Distribute")
if Distribute == true {
let requestURL = NSURL(string: led1on_URL)
// Instantiate an NSURLRequest object using the
// requestURL NSURL
let request = NSURLRequest(url: requestURL! as URL)
// Use the webview to send the request to the
// request NSURLRequest
View1.loadRequest(request as URLRequest)
super.viewDidLoad()
#IBAction func LED_control(_ sender: UIButton) {
}
}
In todayviewcontroller I have:
#IBAction func ButtonSnd(_ sender: Any) {
defaults?.set(true, forKey: "Distribute") //Bool Data Type
//Pass anything with this line
//defaults?.set("\(aNumber)", forKey: "userKey")
defaults?.synchronize()
print("Buttonpressed")
}
}

ios 11 imessage extension message.url does not open safari

I'm adding an iMessage extension target to my app. The extension is supposed to send a message that has a url attribute. The behaviour I'm expecting when a user touches the message is to open the browser using the url attribute of the message.
I have a button in my messageView which executes this code:
#IBAction func labelButton(_ sender: Any) {
let layout = MSMessageTemplateLayout()
layout.imageTitle = "iMessage Extension"
layout.caption = "Hello world!"
layout.subcaption = "Test sub"
guard let url: URL = URL(string: "https://google.com") else { return }
let message = MSMessage()
message.layout = layout
message.summaryText = "Sent Hello World message"
message.url = url
activeConversation?.insert(message, completionHandler: nil)
}
If I touch the message, it expands the MessageViewController
I have then added this:
override func didSelect(_ message: MSMessage, conversation: MSConversation) {
if let message = conversation.selectedMessage {
// message selected
// Eg. open your app:
self.extensionContext?.open(message.url!, completionHandler: nil)
}
}
And now, when I touch the message, it opens my main app but still not my browser.
I have seen on another post (where I cannot comment, thus I opened this post) that it is impossible to open in Safari but I have a news app which inserts links to articles and allows with a click on the message to open the article in a browser window, while the app is installed.
So, can someone please tell how I can proceed to force opening the link in a browser window?
Thank you very much.
Here is a trick to insert a link in a message. It does not allow to create an object that has an url attribute but just to insert a link directly which will open in the default web browser.
activeConversation?.insertText("https://google.com", completionHandler: nil)
I have published a sample on github showing how to launch a URL from inside an iMessage extension. It just uses a fixed URL but the launching code is what you need.
Copying from my readme
The obvious thing to try is self.extensionContext.open which is documented as Asks the system to open a URL on behalf of the currently running app extension.
That doesn't work. However, you can iterate back up the responder chain to find a suitable handler for the open method (actually the iMessage instance) and invoke open with that object.
This approach works for URLs which will open a local app, like settings for a camera, or for web URLs.
The main code
#IBAction public func onOpenWeb(_ sender: UIButton) {
guard let url = testUrl else {return}
// technique that works rather than self.extensionContext.open
var responder = self as UIResponder?
let handler = { (success:Bool) -> () in
if success {
os_log("Finished opening URL")
} else {
os_log("Failed to open URL")
}
}
let openSel = #selector(UIApplication.open(_:options:completionHandler:))
while (responder != nil){
if responder?.responds(to: openSel ) == true{
// cannot package up multiple args to openSel so we explicitly call it on the iMessage application instance
// found by iterating up the chain
(responder as? UIApplication)?.open(url, completionHandler:handler) // perform(openSel, with: url)
return
}
responder = responder!.next
}
}

Make button open link - Swift

This is the code I have now, taken from an answer to a similar question.
#IBAction func GoogleButton(sender: AnyObject) {
if let url = NSURL(string: "www.google.com"){
UIApplication.sharedApplication().openURL(url)
}
}
The button is called Google Button and its text is www.google.com
How do I make it open the link when I press it?
What your code shows is the action that would occur once the button is tapped, rather than the actual button. You need to connect your button to that action.
(I've renamed the action because GoogleButton is not a good name for an action)
In code:
override func viewDidLoad() {
super.viewDidLoad()
googleButton.addTarget(self, action: "didTapGoogle", forControlEvents: .TouchUpInside)
}
#IBAction func didTapGoogle(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://www.google.com")!)
}
In IB:
Edit: in Swift 3, the code for opening a link in safari has changed. Use UIApplication.shared().openURL(URL(string: "http://www.stackoverflow.com")!) instead.
Edit: in Swift 4
UIApplication.shared.openURL(URL(string: "http://www.stackoverflow.com")!)
The string you are supplying for the NSURL does not include the protocol information. openURL uses the protocol to decide which app to open the URL.
Adding "http://" to your string will allow iOS to open Safari.
#IBAction func GoogleButton(sender: AnyObject) {
if let url = NSURL(string: "http://www.google.com"){
UIApplication.sharedApplication().openURL(url)
}
}
if let url = URL(string: "your URL") {
if #available(iOS 10, *){
UIApplication.shared.open(url)
}else{
UIApplication.shared.openURL(url)
}
}
as openUrl method is deprecated in iOS 10, here is solution for iOS 10
let settingsUrl = NSURL(string:UIApplicationOpenSettingsURLString) as! URL
UIApplication.shared.open(settingsUrl, options: [:], completionHandler: nil)
In Swift 4
if let url = URL(string: "http://yourURL") {
UIApplication.shared.open(url, options: [:])
}
if iOS 9 or higher it's better to use SafariServices, so your user will not leave your app.
import SafariServices
let svc = SFSafariViewController(url: url)
present(svc, animated: true, completion: nil)
For Swift 3.0:
if let url = URL(string: strURlToOpen) {
UIApplication.shared.openURL(url)
}
This code works with Xcode 11
if let url = URL(string: "http://www.google.com") {
UIApplication.shared.open(url, options: [:])
}
The code that you have should open the link just fine. I believe, that you probably just copy-pasted this code fragment into your code. The problem is that the UI component (button) in the interface (in storyboard, most likely) is not connected to the code. So the system doesn't know, that when you press the button, it should call this code.
In order to explain this fact to the system, open the storyboard file, where your Google Button is located, then in assistant editor open the file, where your func GoogleButton code fragment is located. Right-click on the button, and drag the line to the code fragment.
If you create this button programmatically, you should add target for some event, for instance, UITouchUpInside. There are plenty of examples on the web, so it shouldn't be a problem :)
UPDATE: As others noted already, you should also add a protocol to the link ("http://" or "https://"). It will do nothing otherwise.
For Swift3 , below code is working fine
#IBAction func Button(_ sender: Any) {
UIApplication.shared.open(urlStore1, options: [:], completionHandler: nil)
}
Actually You Can Use It Like This In Your Action Button Works For Swift 5 :
guard let settingsUrl = URL(string:"https://yourLink.com") else {
return
}
UIApplication.shared.open(settingsUrl, options: [:], completionHandler: nil)
}
// How to open a URL in Safari
import SafariServices \\ import
#IBAction func google(_ sender: Any)
{
if let url = URL(string: "https://www.google.com")
{
let safariVC = SFSafariViewController(url: url)
present(safariVC, animated: true, completion: nil)
}
}
I made this way:
I imported SafariServices
import SafariServices
First step: I defined a button just above viewDidLoad:
let myButton = UIButton()
Second step: I called a function inside viewDidLoad:
func setupMyButton() {
view.addSubview(myButton)
myButton.configuration = .plain()
myButton.configuration?.cornerStyle = .capsule
myButton.configuration?.title = "Go to Google"
myButton.addTarget(self, action: #selector(selector), for: .touchUpInside)
myButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
myButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
myButton.centerYAnchor.constraint(equalTo: view.centerYAnchor),
myButton.widthAnchor.constraint(equalToConstant: 200),
myButton.heightAnchor.constraint(equalToConstant: 50),
])
}
Third step: At the bottom of the scope, I called an #objc func to use as selector. (Outside viewDidLoad)
#objc func selector() {
if let url = URL(string: "https://www.google.com")
{
let safariVC = SFSafariViewController(url: url)
present(safariVC, animated: true, completion: nil)
}
}
And I did not forget to call my func at the beginning of the viewDidLoad:
setupMyButton()
A dude named PRAVEEN BHATI helped me at the third step.
Hope this helps.

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