i want to go to a url by clicking on button. I tried using 'UISharedapplication'and also through the method below mentioned but none works. Please help.
Thanks.
#IBAction func Displayurl(_ sender: Any) {
UIApplication.shared.canOpenURL(NSURL (string: "http://www.apple.com")! as URL)
}
The issue is that UIApplication's canOpenURL() method simply returns whether a URL can be opened, and does not actually open the URL. Once you've determined whether the URL can be opened (by calling canOpenURL(), as you have done), you must then call open() on the shared UIApplication instance to actually open the URL. This is demonstrated below:
if let url = URL(string: "http://www.apple.com") {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:])
}
}
open() also takes an optional completionHandler argument with a single success parameter that you can choose to implement to determine if the URL was successfully opened.
canOpenURL(_:) method is used whether there is an installed app that can handle the url scheme. To open the resource of the specified URL use the open(_:options:completionHandler:) method. As for example
if let url = URL(string: "apple.com") {
if UIApplication.shared.canOpenURL(url) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}
For more info check the documentation here https://developer.apple.com/documentation/uikit/uiapplication/1622961-openurl
Related
I have an Instagram scheduling app and I am trying to open this (see image below) in Swift 5.x. The goal is simple: save Image to Firebase, once it is time to post, notification!, user clicks on the notification and this (image below) opens up with the appropriate image/video to post. Everything works except for opening Instagram with the appropriate photo/video. I have tried this:
func postToInstagram(image: URL) {
let videoFileUrl: URL = image
var localId: String?
PHPhotoLibrary.shared().performChanges({
let request = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoFileUrl)
localId = request?.placeholderForCreatedAsset?.localIdentifier
}, completionHandler: { success, error in
// completion handler is called on an arbitrary thread
// but since you (most likely) will perform some UI stuff
// you better move everything to the main thread.
DispatchQueue.main.async {
guard error == nil else {
// handle error
print(error)
return
}
guard let localId = localId else {
// highly unlikely that it'll be nil,
// but you should handle this error just in case
return
}
let url = URL(string: "instagram://library?LocalIdentifier=\(localId)")!
guard UIApplication.shared.canOpenURL(url) else {
// handle this error
return
}
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
})
}
and this:
func postToInstagram(image: URL, igURL: String) {
let urlStr: String = "instagram://app"
let url = URL(string: igURL)
if UIApplication.shared.canOpenURL(url!) {
print("can open")
UIApplication.shared.open(url!, options: [:], completionHandler: nil)
}
}
To no avail. The latter code works, but only opens the Instagram app itself, which is fine, but I would like to open the View in the image below rather than Instagram's home screen. I also tried changing the URL to "instagram://share" and this works but goes to publish a regular post, whereas I want the user to decide what they want to do with their image.
This is where I want to go:
Note: For everyone who will be telling me this and whoever will wonder: Yes, my URL schemes (LSApplicationQueriesSchemes) are fine. And, just to clarify, I need to fetch the image/video from Firebase before posting it.
The task is quite simple. With a given urlString open it when it is valid. This is what I tried:
func openURL(_ urlString: String) {
guard let url = URL(string: urlString) else {
showInvalidUrlAlert()
return
}
UIApplication.shared.open(url)
}
This work with this example: "https://www.google.de/?hl=de"
However when passing an invalid url, which is also possible in my application (for example: "asdfd") I get this error on the console but nothing happens in the app:
[default] Failed to open URL asdf: Error Domain=NSOSStatusErrorDomain Code=-50 "invalid input parameters" UserInfo={NSDebugDescription=invalid input parameters, _LSLine=252, _LSFunction=-[_LSDOpenClient openURL:options:completionHandler:]}
What is the best practice here?
You may want to use the completionHandler parameter:
func openURL(_ urlString: String) {
guard let url = URL(string: urlString) else {
showInvalidUrlAlert()
return
}
UIApplication.shared.open(url, completionHandler: { success in
if success {
print("opened")
} else {
print("failed")
// showInvalidUrlAlert()
}
})
}
Inside of guard statement, you can throw an exception created by your application instead only put a return, like this:
guard let urlString = url, !urlString.isEmpty, let url = URL(string: urlString) else {
throw ErrorEnum.invalidURL
}
With this approach, you can catch the error and send a UI Feedback for the User where it calls de func openURL.
Did the URL have a http or https scheme attached? to open a website, you must require the String to have http(s). other wise the application won't know how to handle it, since it also handles other protocols.
...supports many common schemes, including the http, https, tel, facetime, and mailto schemes...
https://developer.apple.com/documentation/uikit/uiapplication/1648685-open
I run the shortcuts with the x-callback url given below code:
let url = URL(string: "shortcuts://x-callback-url/run-shortcut?name=Airplane&x-success=shortcutsdemo://")
UIApplication.shared.open(url!, options: [:], completionHandler: nil)
When I open the URL in UIApplication.shared.open, it runs the shortcut and after its done, return back to our iOS app.
My question is if my shortcut is not added in shortcuts app, how I manage?
Is there any way to first find our shortcut is added or not in shortcuts app and then we run the shortcut.
Like :
if (Shortcut.isInstalled) {
let url = URL(string: "shortcuts://x-callback-url/run-shortcut?name=Airplane&x-success=shortcutsdemo://")
UIApplication.shared.open(url!, options: [:], completionHandler: nil)
} else {
print("Not installed")
}
Summary :
If the shortcut is added in our shortcuts app, Then it's run the shortcuts using our iOS app. Otherwise its not run. and give an error for that shortcut.
I think you will need to use func canOpenURL(_ url: URL) -> Bool
let url = URL(string: "shortcuts://x-callback-url/run-shortcut?name=Airplane&x-success=shortcutsdemo://")
if UIApplication.shared.canOpenURL(ur!l) {
print("Short uts is installed")
} else {
print("Shortcuts not installed")
}
I am not 100% sure, but I think it redirects you automatically to appstore if you don't have it, check that out.
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)
}