I am trying to share a picture from my app to Telegram. I want to do this without UIActivityViewController if possible. I have bellow the code that almost does exactly what I want. It opens telegram, it lets me choose who to send to, but it doesn't share the picture, only a url path.
This is the code that I've wrote:
In the following code, url is address to the image on the phone that I'm trying to share.
let telegramUrlString = "tg://msg_url?url=\(url)"
if let urlString = telegramUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
if let telegramUrl = URL(string: urlString) {
if UIApplication.shared.canOpenURL(telegramUrl) {
UIApplication.shared.open(telegramUrl, options: [:], completionHandler: nil)
} else {
completion(ErrorCode.CANNOT_SHARE_ON_TELEGRAM, nil)
}
}
}
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.
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.
I have my app running on my iPhone, and I'm able to send some data to my WhatsApp from my App. I went through the following to do the same :
Sending message to WhatsApp from your app using Swift?
Is there a way we can create a URL that would open our own app directly if it is installed? Could someone suggest any place where I could understand how it could be done?
Something like this should work:
let originalString = "Some text you want to send"
let encodedString = originalString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
let url = NSURL(string: "whatsapp://send?text="+encodedString!)
if UIApplication.sharedApplication().canOpenURL(url!) {
UIApplication.sharedApplication().open(url as URL, options: [:]) { (success) in
if success {
print("WhatsApp accessed successfully")
} else {
print("Error accessing WhatsApp")
}
}
} else {
print("whatsapp not installed")
}
I'm trying to send an email from my app. But what I want is if user is having Gmail app on his/her phone, then mail should be sent using it. If Gmail app is unavailable then the user should be redirected to Mailbox.
So how can I know if user contains Gmail app and how can I redirect user to it.
Setup for iOS9+
As explained here, if you're on iOS9+, don't forget to add googlegmail to LSApplicationQueriesSchemes on your info.plist
Code to open GMail
Then, you can do the same as the accepted answer (below is my swift 2.3 version):
let googleUrlString = "googlegmail:///co?subject=Hello&body=Hi"
if let googleUrl = NSURL(string: googleUrlString) {
// show alert to choose app
if UIApplication.sharedApplication().canOpenURL(googleUrl) {
if #available(iOS 10.0, *) {
UIApplication.sharedApplication().openURL(googleUrl, options: [:], completionHandler: nil)
} else {
UIApplication.sharedApplication().openURL(googleUrl)
}
}
}
You need to use custom URL Scheme. For gmail application its:
googlegmail://
If you want to compose a message there you can add more parameters to this URL:
co?subject=Example&body=ExampleBody
You can determinate if any kind of application is installed using this code (just replace customURL obviously for an other apps):
NSString *customURL = #"googlegmail://";
if ([[UIApplication sharedApplication]
canOpenURL:[NSURL URLWithString:customURL]])
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];
}
else
{
//not installed, show popup for a user or an error
}
For Swift 3.0+
Notes:
This solution shows how to use spaces or newlines in the arguments to the URL (Gmail may not respect the newlines).
It is NOT necessary to register with LSApplicationQueriesSchemes as long as you don't call canOpenURL(url). Just try and use the completion handler to determine if it succeeded.
let googleUrlString = "googlegmail:///co?to=\(address.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? "")&subject=\(subject.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? "")&body=\(buildInfo.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? "")"
if let googleUrl = URL(string: googleUrlString) {
UIApplication.shared.open(googleUrl, options: [:]) {
success in
if !success {
// Notify user or handle failure as appropriate
}
}
}
else {
print("Could not get URL from string")
}
I couldn't figure out why this wasn't working for me until I realised I was targetting a info_development.plist instead of the production-file info.plist
If you're like me and happen to have multiple Plists (one for development, one for prod etc) make sure you edit it everywhere. ;-)
Swift 5
These answers can open gmail but what if the user do not have gmail installed in the device? In that case I have handled opening apple mail/outlook/yahoo/spark. If none of them are present, I am showing an alert.
#IBAction func openmailAction() {
if let googleUrl = NSURL(string: "googlegmail://") {
openMail(googleUrl)
} else if let mailURL = NSURL(string: "message://") {
openMail(mailURL)
} else if let outlookURL = NSURL(string: "ms-outlook://") {
openMail(outlookURL)
} else if let yahooURL = NSURL(string: "ymail://") {
openMail(yahooURL)
} else if let sparkUrl = NSURL(string: "readdle-spark://") {
openMail(sparkUrl)
} else {
// showAlert
}
}
func openMail(_ url: NSURL) {
if UIApplication.shared.canOpenURL(url as URL) {
UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
}
}
You might also may have to add this in the plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>googlegmail</string>
<string>ms-outlook</string>
<string>readdle-spark</string>
<string>ymail</string>
</array>
Is it possible to share Image and Text from an iOS app to WhatsApp using UIDocumentIntractionController or API in iPhone application development?
Please look at this link from the FAQ:
http://www.whatsapp.com/faq/en/iphone/23559013
I have found that If your application creates photos, videos or audio notes and you’d like your users to share these media using WhatsApp, you can use the Document Interaction API to send your media to your WhatsApp contacts and groups.
You can refer this link : http://www.whatsapp.com/faq/en/iphone/23559013
In Swift 3 use this code
#IBAction func whatsappShareWithImages(_ sender: AnyObject)
{
let urlWhats = "whatsapp://app"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed) {
if let whatsappURL = URL(string: urlString) {
if UIApplication.shared.canOpenURL(whatsappURL as URL) {
if let image = UIImage(named: "whatsappIcon") {
if let imageData = UIImageJPEGRepresentation(image, 1.0) {
let tempFile = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.wai")
do {
try imageData.write(to: tempFile, options: .atomic)
self.documentInteractionController = UIDocumentInteractionController(url: tempFile)
self.documentInteractionController.uti = "net.whatsapp.image"
self.documentInteractionController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)
} catch {
print(error)
}
}
}
} else {
// Cannot open whatsapp
}
}
}
}
Add this code in your app "plist"
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>
You can also refer to small app for reference : https://github.com/nithinbemitk/iOS-Whatsapp-Share