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.
Related
I am trying to create a button that goes to a link when pressed using Swift 3. When I run the app and click the button, nothing happens. Here is the code for the button's #IBAction:
#IBAction func facebookButton(_ sender: AnyObject) {
if let url = NSURL(string: "http://www.facebook.com/MatchWear-1638094356470603/info?tab=overview"){
UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
}
}
Assuming that you are pretty sure that the #IBAction is connected to your button, it should looks like this:
if let url = URL(string: "http://www.facebook.com/MatchWear-1638094356470603/info?tab=overview") , UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
} else {
// invalid URL...
}
Hope this helped.
I have a UIButton in my UICollectionViewCell and it's getting data from JSON. Now I need to open a URL from each button (each button have a different url that also comes from JSON).
I managed to open the URL with:
let weburl = "http://example.com"
UIApplication.shared.openURL(URL(string: weburl)!)
But now I need to kinda pass an url to each button. Any ideas of how can i achieve this?
You can have an array of urls:
let urls = [url1, url2, ...]
And then assign the tag property of each button to the index of its corresponding url. Now you can easily manage what you want:
#IBAction func handleTouch(_ sender: UIButton) {
// assumes that the buttons' tags start at 0, which isn't a good idea.
// see #rmaddy comment bellow
let url = urls[sender.tag]
// use the version of the open method shown bellow because the other one becomes deprecated in iOS 10
UIApplication.shared.open(URL(string: url)!, options: [:], completionHandler: nil)
}
EDIT
Other solution would be to just store the url in the cell itself, and in the button handler open the url corresponding to its cell.
FYI openURL is deprecated in iOS 10. I suggest the following if you need to support older versions of ios:
let url = URL(string: "alexa://")!
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler: {
(success) in
guard success else {
//Error here
}
//Success here
})
} else {
if let success = UIApplication.shared.openURL(url) {
//Success here
} else {
//Error here
}
}
Otherwise just use UIApplication.shared.open. Also I would add a URL field to the data model you are passing to your tableViewCell and just look up the URL from the model.
Hello I've button action for call number , but when I used it don't call and nothing shows.
My codes under below.
#IBAction func callPhone(sender: AnyObject) {
UIApplication.shared().canOpenURL((NSURL(string: "tel://1234567890")! as URL))
}
Thank You !
Proper Swift 3.0 Code
if let url = URL(string: "tel://\(phoneNumber)") {
UIApplication.shared().open(url, options: [:], completionHandler: nil)
}
In Swift 3.0 NSURL have changed to URL. And sharedApplciation changed to shared. Also OpenURL changed to open, they have added a bunch other parameters to the openmethod, you can pass empty dictionary in options and nil in the completionHandler.
Please try following code it's use to solve your problem.
if let url = NSURL(string: "tel://\(1234567890)") {
UIApplication.sharedApplication().openURL(url)
}
Try this answer.
#IBAction func callPhone(sender: AnyObject) {
if let url = NSURL(string: "tel://9069118117") {
UIApplication.sharedApplication().openURL(url)
}
}
please note that:
tel:// try to call direct the phone number;
telprompt:// shows you an alert to confirm call
as of iOS 10 openUrl is deprecated;
#available(iOS, introduced: 2.0, deprecated: 10.0, message: "Please use openURL:options:completionHandler: instead")
open func openURL(_ url: URL) -> Bool
so i advice to use this code block to support also iOS < 9:
if #available(iOS 10, *) {
UIApplication.shared.open(yourURL)
// if you need completionHandler:
//UIApplication.shared.open(yourURL, completionHandler: { (aBool) in })
// if you need options too:
//UIApplication.shared.open(yourURL, options: [:], completionHandler: { (aBool) in })
} else {
UIApplication.shared.openURL(number)
}
Latest Xcode , Latest Swift working codes.
use telprompt:// not tel
let myphone = "+134345345345"
if let phone = URL(string:"telprompt://\(myphone)"), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
}
It seems I can't open the second app using my method. Nothing happened. Is there any silly mistakes here?
My second app .plist file
My first app code
#IBAction func btnCRM(sender: AnyObject) {
var customURL: NSString = "CRM://"
if (UIApplication.sharedApplication().canOpenURL(NSURL(fileURLWithPath: customURL as String)!)){
UIApplication.sharedApplication().openURL(NSURL(fileURLWithPath: customURL as String)!)
}
}
In addition to the URL Schemes under Item 0, you need to add URL identifier which is CFBundleURLName, as outlined here.
try this code:
let url = NSURL(string: "CRM://")
if (UIApplication.sharedApplication().canOpenURL(url!)) {
UIApplication.sharedApplication().openURL(url!)
}
'openURL' was deprecated in iOS 10.0
Updated version:
guard let url = URL(string: "CRM://"), UIApplication.shared.canOpenURL(url) else {
return
}
UIApplication.shared.open(url, options: [:], completionHandler: nil)
Swift 5.7 2023
The code below opens the main application
private func openMainApp() {
self.extensionContext?.completeRequest(returningItems: nil, completionHandler: { _ in
guard let url = URL(string: self.appURL) else {
return
}
_ = self.openURL(url)
})
}
// Courtesy: https://stackoverflow.com/a/44499222/13363449 👇🏾
// Function must be named exactly like this so a selector can be found by the compiler!
// Anyway - it's another selector in another instance that would be "performed" instead.
#objc private func openURL(_ url: URL) -> Bool {
var responder: UIResponder? = self
while responder != nil {
if let application = responder as? UIApplication {
return application.perform(#selector(openURL(_:)), with: url) != nil
}
responder = responder?.next
}
return false
}
I am creating an app, and I have a banner which promotes my other app. This is my code:
var barsButton : UIButton = UIButton(frame: CGRectMake((self.view.bounds.width / 2) - 51, self.view.bounds.height - 100, 102, 30))
barsButton.setImage(UIImage(named: "Bars Icon 2.png"), forState: .Normal)
barsButton.addTarget(self, action: "openBarsLink", forControlEvents: UIControlEvents.TouchUpInside)
func openBarsLink() {
var barsLink : String = "itms-apps:https://itunes.apple.com/app/bars/id706081574?mt=8"
UIApplication.sharedApplication().openURL(NSURL.URLWithString(barsLink))
}
However, when the user presses the button, it just takes them to the App Store, and not the specific page for my app. What am I doing wrong?
You have too many protocols in your URL. Get rid of https: so the URL reads
itms-apps://itunes.apple.com/app/bars/id706081574
Just by following older answers I couldn't make it work, so here I post my complete solution:
if let url = NSURL(string: "itms-apps://itunes.apple.com/app/id1234567890"),
UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
}
}
Use just the short "itms://".
For Swift 3 this is the snippet:
UIApplication.shared.openURL(URL(string: "itms://itunes.apple.com/app/id" + appStoreAppID)!)
I hope this helps someone.
Cheers.
P.S. #Eric Aya was ahead of the time :)
I had this problem but this code just works on the phone not simulator. So check this code:
if let url = URL(string: "itms-apps://itunes.apple.com/app/id" + APP_ID ),
UIApplication.shared.canOpenURL(url){
UIApplication.shared.openURL(url)
}else{
//Just check it on phone not simulator!
print("Can not open")
}
As openURL is deprecated from iOS 10 use below code:
UIApplication.shared.open((URL(string: "itms://itunes.apple.com/app/" + appStoreAppID)!), options:[:], completionHandler: nil)
Simply you can use these functions in a utility struct to goto app page in app store also you can goto rate app view directly:
static func gotoApp(appID: String, completion: ((_ success: Bool)->())? = nil) {
let appUrl = "itms-apps://itunes.apple.com/app/id\(appID)"
gotoURL(string: appUrl, completion: completion)
}
static func rateApp(appId: String, completion: ((_ success: Bool)->())? = nil) {
//let appUrl = "itms-apps://itunes.apple.com/app/" + appId
let appUrl = "https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=\(appId)&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8"
//TODO: use &action=write-review for opening review directly
print("app review URL: ", appUrl)
gotoURL(string: appUrl, completion: completion)
}
static func gotoURL(string: String, completion: ((_ success: Bool)->())? = nil) {
print("gotoURL: ", string)
guard let url = URL(string: string) else {
print("gotoURL: invalid url", string)
completion?(false)
return
}
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler: completion)
} else {
completion?(UIApplication.shared.openURL(url))
}
}
Swift 3 - XCode 8.2.1
UIApplication.shared.openURL(URL(string: "itms-apps://itunes.apple.com/app/id" + appStoreAppID)!)
Link you are trying to open is not valid - remove https: schema from it (or itms: - but I suggest first option, to avoid redirects)
I use this and it works.
let locale: String = Locale.current.regionCode ?? "US"
UIApplication.shared.open(URL(string: "https://apps.apple.com/\(locale)/developer/{developer-name}/{idXXXXXXXXXX}")!, options: [:], completionHandler: nil)