How to add a hyperlink button on iOS Swift? - ios

I'm trying to make a clickable link over a button.
I made this using some Internet help but it didn't work :
#IBAction func linkClicked(sender: AnyObject) {
openUrl("http://fr.envisite.net/t5exce")
}
func openUrl(url:String!) {
let targetURL=NSURL(fileURLWithPath: url)
let application=UIApplication.sharedApplication()
application.openURL(targetURL);
}
It doesn't do anything, no error, just the button doesn't get me on Safari (I use the iOS simulator)

You're creating a file URL with a web url string. Use the NSURL String constructor instead.
#IBAction func linkClicked(sender: AnyObject) {
openUrl("http://fr.envisite.net/t5exce")
}
func openUrl(urlStr:String!) {
if let url = NSURL(string:urlStr) {
UIApplication.sharedApplication().openURL(url)
}
}
Swift3
#IBAction func linkClicked(sender: Any) {
openUrl(urlStr: "http://fr.envisite.net/t5exce")
}
func openUrl(urlStr: String!) {
if let url = URL(string:urlStr), !url.absoluteString.isEmpty {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}

Related

Xcode Button Going to the Wrong Link

my app currently has two buttons. One leads to a Twitter page, and the other links to a page on my Website. They are both on the same view controller and same view. However, when I click the Feedback button, it goes to my Twitter. Any advice?
Here's my code.
import UIKit
class AboutScreenViewController: UIViewController {
#IBAction func twitterButton(_ sender: Any) {
if let url2 = URL(string: "https://twitter.com/SunnyParks4u") {
UIApplication.shared.open(url2, options: [:], completionHandler: nil)
}
}
#IBAction func FeedbackButton(_ sender: Any) {
if let Contactlink = URL(string: "https://sunnyparks4u.wixsite.com/home-page/contact-8") {
UIApplication.shared.open(Contactlink, options: [:], completionHandler: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
Maybe You copy/pasted the button in the interface builder and now both of the buttons executes the same IBAction.
Right-click on both buttons and check

Create action for invites

In my iOS application, I want to put a feature which will send invites to people selected in other applications like WhatsApp or other messaging services. I have no idea how to go about it. Please help me in this regard. A little guidance will be appreciated.
I tried to use WhatsApp to send invites. But I was unable to achieve it.
#IBAction func invite(_ sender: UIButton) {
let ReferCode = UserDefaults.standard.string(forKey: "ReferCode") ?? ""
let originalString = ReferCode
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed)
let url = URL(string: "whatsapp://send?text= Your referral code is\(escapedString!)")
if UIApplication.shared.canOpenURL(url! as URL)
{
if #available(iOS 10.0, *) {
UIApplication.shared.open(url! as URL, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
}
}
}
When I am pressing the invite button, the app is crashing.
If you are getting nil value in referCode then it might be crash. use conditional unwrapping for optional values.
#IBAction func invite(_ sender: UIButton) {
guard let referCode = UserDefaults.standard.string(forKey: "ReferCode") else {
debugPrint("referCode not available")
return
}
let escapedString = referCode.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed)
guard let url = URL(string: "whatsapp://send?text= Your referral code is \(String(describing: escapedString))") else {
debugPrint("URL not correct")
return
}
if UIApplication.shared.canOpenURL(url)
{
if #available(iOS 10.0, *) {
UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
}
}
}

Open Safari from my Today Extension (widget) within my app

I have a Today Extension with a text field. I want to use the contents of the text field as a URL to open a browser within my app.
This is my TodayViewController.swift for my widget
import UIKit
import SafariServices
import NotificationCenter
// This extension to remove the white spaces from what pasteed
extension String {
func replace(string:String, replacement:String) -> String {
return self.replacingOccurrences(of: string, with: replacement,
options: NSString.CompareOptions.literal, range: nil)
}
func removeWhitespace() -> String {
return self.replace(string: " ", replacement: "")
}
}
class TodayViewController: UIViewController, NCWidgetProviding {
var clearNumber: String?
override func viewDidLoad() {
super.viewDidLoad()
}
func widgetPerformUpdate(completionHandler: (#escaping (NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
completionHandler(NCUpdateResult.newData)
}
#IBOutlet weak var textBox: UITextField!
#IBAction func clearNumber(_ sender: Any) {
if textBox.hasText == true {
textBox.text = ""
}else{
return
}
}
#IBAction func pasteNumber(_ sender: Any) {
if let myString = UIPasteboard.general.string {
let pasteNumber = myString.removeWhitespace()
textBox.insertText(pasteNumber)
}else{
return
}
}
#IBAction func goButton(_ sender: Any) {
let myAppUrl = URL(string: "main-screen:")!
extensionContext?.open(myAppUrl, completionHandler: { (success) in
if (!success) {
print("error: failed to open app from Today Extension")
}
})
}
You could use #Giuseppe_Lanza solution and parse url that you receive from Today Extension Widget. However, I would show an example where your url have a static components and looking for a path such as https:/www.apple.com/homepod or https:/www.apple.com/iphone based on user's input in the textField:
1- URL Scheme: myAppName
2- Add this to open your app with widget
#IBAction func goButton(_ sender: Any) {
openApp(widgetText: "\(textBox.text!)")
}
func openApp(widgetText:String) {
let str = "myAppName://https://www.apple.com/\(widgetText)"
let url = URL(string: str)!
if textBox.hasText == true {
extensionContext?.open(url, completionHandler: { (success) in
if (!success) {
print("error: 🧐")
}
})
}
}
3- AppDelegate
Define a variable and pass received url to webViewController, will parse url there.
open var receivedUrl:URL?
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool{
receivedUrl = url
//You need to alter this navigation to match your app requirement so that you get a reference to your previous view..
window?.rootViewController?.performSegue(withIdentifier: "toDeepLink", sender: nil)
}
Make sure to make add an identifier for this segue under the attributes
inspector as toDeepLink.
4- WebView & parsing url
Now you can get the receivedUrl like this
override func viewDidLoad() {
super.viewDidLoad()
let myAppDelegate = UIApplication.shared.delegate as! AppDelegate
print("receivedUrl \(myAppDelegate.receivedUrl!)")
//url Parsing & getting rid off urlScheme
let urlToLoad = URL(string: "\(myAppDelegate.receivedUrl!.host! + ":" + myAppDelegate.receivedUrl!.path)")!
print(urlToLoad)
let urlRequest = URLRequest(url: urlToLoad)
webView.load(urlRequest)
}
Else, you need to parse it in a proper way like dictionary to assign dynamic values to respective keys in your dictionary and hence to your url or append "?" to your urlToLoad just before you attempt to append url.query as I did in the webView controller.
You can do this by using deep linking.
First define a custom URL scheme
Once your app responds to the custom scheme my-app:// you can open your app from your todayViewController.
#IBAction func goButton(_ sender: Any) {
let myAppUrl = URL(string: "my-app://openurl/\(yourURL.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed))")!
extensionContext?.open(myAppUrl, completionHandler: { (success) in
if (!success) {
print("error: failed to open app from Today Extension")
}
})
}
In your app, just like described in the previous link you will have to implement in your app delegate
func application(_ app: UIApplication, open url: URL,
options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool
in this method, the url will be the one you created in your app extension. Meaning it will be my-app://openurl/{the url with percent escaping} You will have to parse this url, initialise the view controller that contains the webView and pass the url to be opened.

How to Share on Facebook and Twitter App in Swift 3 without SDK

I need to share some link on facebook and twitter app if installed in device on a button tap.I can share the same using Whatsapp (code is below).I want to know if i can do the same in facebook and twitter app also.
#IBAction func whatsappbtn(_ sender: UIButton) {
var str = "This is the string which you want to share to WhatsApp"
str=str.addingPercentEncoding(withAllowedCharacters: (NSCharacterSet.urlQueryAllowed))!
let whatsappURL = URL(string: "whatsapp://send?text=\(str)")
if UIApplication.shared.canOpenURL(whatsappURL!) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(whatsappURL!, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
}
} else {
self.delegate?.alerting(msg: "Please install Whatsapp and try again.")
}
}
If you are bound not to use FB / Twitter SDK . then you can try using activity controller and share from your app . Here you will get every possible share option .
var activityViewController:UIActivityViewController?
textField .text = "Some Test"
#IBAction func shareText(sender: UIButton) {
activityViewController = UIActivityViewController(
activityItems: [textField.text as NSString],
applicationActivities: nil)
presentViewController(activityViewController, animated: true, completion: nil)
}
First you need to get the FBSDK from Facebook's developer website.
Then you can do something like this:
func shareToFacebook() {
let inviteDialog = FBSDKAppInviteDialog()
if inviteDialog.canShow() {
guard let appLinkURL = URL(string: "YOUR LINK") else { return }
guard let previewImageURL = URL(string: "YOUR LINK IMAGE") else { return }
let inviteContent = FBSDKAppInviteContent()
inviteContent.appLinkURL = appLinkUrl
inviteContent.appInvitePreviewImageURL = previewImageURL
inviteDialog.content = inviteContent
inviteDialog.delegate = self
inviteDialog.show()
}
}
Don't forget to set the delegate methods:
func appInviteDialog(_ appInviteDialog: FBSDKAppInviteDialog!, didCompleteWithResults results: [AnyHashable : Any]!) {
print("Did complete sharing.. ")
}
func appInviteDialog(_ appInviteDialog: FBSDKAppInviteDialog!, didFailWithError error: Error!) {
print("Error tool place in appInviteDialog \(error)")
}
The above works for Swift 3+
Let me know if it works for you. Cheers

How do I open Instagram app from my iOS app?

I am trying to open the Instagram application from my iOS app through UIButton action but it's not working. It shows nothing.
Here is my code in Swift 3:
#IBAction func Instagram(_ sender: AnyObject) {
let instagramURL = URL(string: "instagram://app")!
if UIApplication.shared.canOpenURL(instagramURL) {
UIApplication.shared.openURL(instagramURL)
}
For swift 4.2+ and ios 9+
This code launch Instagram, if it's not installed, launch the Instagram profile page in a web browser.
let screenName = "mehdico" // CHANGE THIS
let appURL = URL(string: "instagram://user?username=\(screenName)")
let webURL = URL(string: "https://instagram.com/\(screenName)")
if UIApplication.shared.canOpenURL(appURL) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(appURL, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(appURL)
}
} else {
//redirect to safari because the user doesn't have Instagram
if #available(iOS 10.0, *) {
UIApplication.shared.open(webURL, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(webURL)
}
}
The method openUrl which you have posted in comments in deprecated too in iOS 10
Use this
#IBAction func openInstagramButtonPressed(_ sender: Any) {
let instagram = URL(string: "instagram://app")!
if UIApplication.shared.canOpenURL(instagram) {
UIApplication.shared.open(instagram, options: ["":""], completionHandler: nil)
} else {
print("Instagram not installed")
}
}
For the first time it will prompt you to open or cancel.
Also make sure to do the LSApplicationQueriesSchemes entry for instagram which you had already done.

Resources