Deeplink not work with SocialSharing - ionic-framework

I'm developing an ionic project.
I have follwed all steps to installa Social Sharing and Deeplinks.
This is my schema when I install plugin.
ionic cordova plugin add ionic-plugin-deeplinks --variable URL_SCHEME=app --variable DEEPLINK_SCHEME=https --variable DEEPLINK_HOST=app.com --variable ANDROID_PATH_PREFIX=/
But when I share with Social Sharing don't send a url, Social Sharing send as string or via email send some structure as string an other part as url.
e.g. via hangout as string
e.g. via email app://app.com/page --> app:// as string and app.com/page as url
In Social share documentation schema is share(meesage, subject, file, url)
message:string, subject:string, file:string|Array, url:string
this.socialSharing.share('Lorem ipsum', 'title', null, 'app://app.com/about')
.then( ()=> {
console.log('Success');
})
.catch( (error)=> {
console.log('Error: ', error);
});
The app open deeplinks when I tested using browser from codepen.io with hiperlink.
< h1 >< a href="app://app.com/about" >Click Me< /a>< /h1>
But when I share a deeplink send as string.
Why??? Can you help me???

I struggled with the same problem, the solution to this is very straight forward:
Do not use custom url schemes
The main reason for not using custom url schemes is that Gmail and other webmail provider indeed destroys links such as "app://...". So there is no way to get this work.
See the following links for details:
Make a link in the Android browser start up my app?
https://github.com/EddyVerbruggen/Custom-URL-scheme/issues/81
Use universal links instead
Universal links is supported by Android und iOS. Since you are already using the ionic-plugin-deeplinks plugin, you already configured a deeplink url.
All you have to do is change
href="app://app.com/about"
to
href="https://app.com/about"
For using universal links you need to create configuration files for android and iOS. These files must include application identifiers for all the apps with which the site wants to share credentials. See the following link for details:
https://medium.com/#ageitgey/everything-you-need-to-know-about-implementing-ios-and-android-mobile-deep-linking-f4348b265b49
The file has to be located on your website at exactly
https://www.example.com/.well-known/apple-app-site-association (for iOS)
https://www.example.com/.well-known/assetlinks.json (for android)

You can also use to get data from custom URL and deep link in our app if exist. Otherwise, redirect to play/app store like this:
index.html
$(document).ready(function (){
var lifestoryId = getParameterByName('lifestoryId');
if(navigator.userAgent.toLowerCase().indexOf("android") > -1){
setTimeout(function () {
window.location.href = "http://play.google.com/store/apps/details?id=com.android.xyz&hl=en";
}, 5000);
}
if(navigator.userAgent.toLowerCase().indexOf("iphone") > -1){
setTimeout(function () {
window.location.href = "https://itunes.apple.com/us/app/app/id12345678?ls=1&mt=8";
}, 5000);
}
window.location.href = "app://lifestory/info:"+lifestoryId;
});
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
Call link like: BASE_URL/index.html?lifestoryId=123

Related

Unable to open PDF files in app view in Capacitor Ionic

import { Plugins } from '#capacitor/core';
const { Browser } = Plugins;
Browser.open({ url: 'http://www.africau.edu/images/default/sample.pdf', windowName:'_self' });
When the url is specified as a link to a website, it works fine but doesnt when specified a PDF. Could someone please suggest if any changes required ? Do i need to specify the rel ? If yes how ? There is no such key to be passed in open call. Response received is 'NO enabled plugin supports this MIME type'.
The Browser plugin from Capacitor should work fine for this. Try without specifying windowName.
// Capacitor v2
import { Plugins } from '#capacitor/core';
const { Browser } = Plugins;
Browser.open({ url: 'http://www.africau.edu/images/default/sample.pdf'});
// or for Capacitor v3
import { Browser } from '#capacitor/browser';
Browser.open({ url: 'http://www.africau.edu/images/default/sample.pdf'});
InAppBrowser will not pdf files. you will have to use it in some other way,
first you can simply add a href this will open user default browser.. like for android it will open this link in android and for ios it will use safari.
open pdf
Second way is to use a plugin for document viewer .. i have added its link below
constructor(private document: DocumentViewer) { }
const options: DocumentViewerOptions = {
title: 'My PDF'
}
this.document.viewDocument('http://www.africau.edu/images/default/sample.pdf', 'application/pdf', options)
https://ionicframework.com/docs/native/document-viewer

Flutter open whatsapp with text message

I want to open whatsapp from my Flutter application and send a specific text string. I'll select who I send it to when I'm in whatsapp.
After making some research I came up with this:
_launchWhatsapp() async {
const url = "https://wa.me/?text=Hey buddy, try this super cool new app!";
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
Which works ok ish, however there are two problems:
As soon as I make the text string into multi words it fails. So if I change it to:
_launchWhatsapp() async {
const url = "https://wa.me/?text=Hey buddy, try this super cool new app!";
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
Then the Could not launch $url is thrown.
I have whatsapp already installed on my phone, but it doesn't go directly to the app, instead it gives me a webpage first and the option to open the app.
Here is the webpage that I see:
Any help on resolving either of these issues would be greatly appreciated.
Thanks
Carson
P.s. I'm using the Url_launcher package to do this.
From the official Whatsapp FAQ, you can see that using "Universal links are the preferred method of linking to a WhatsApp account".
So in your code, the url string should be:
const url = "https://wa.me/?text=YourTextHere";
If the user has Whatsapp installed in his phone, this link will open it directly. That should solve the problem of opening a webpage first.
For the problem of not being able to send multi-word messages, that's because you need to encode your message as a URL. Thats stated in the documentation aswell:
URL-encodedtext is the URL-encoded pre-filled message.
So, in order to url-encode your message in Dart, you can do it as follows:
const url = "https://wa.me/?text=Your Message here";
var encoded = Uri.encodeFull(url);
As seen in the Dart Language tour.
Please note that in your example-code you have put an extra set of single quotes around the text-message, which you shouldn't.
Edit:
Another option also presented in the Whatsapp FAQ is to directly use the Whatsapp Scheme. If you want to try that, you can use the following url:
const url = "whatsapp://send?text=Hello World!"
Please also note that if you are testing in iOS9 or greater, the Apple Documentation states:
Important
If your app is linked on or after iOS 9.0, you must declare the URL schemes you pass to this method by adding the LSApplicationQueriesSchemes key to your app's Info.plist file. This method always returns false for undeclared schemes, whether or not an appropriate app is installed. To learn more about the key, see LSApplicationQueriesSchemes.
So you need to add the following keys to your info.plist, in case you are using the custom whatsapp scheme:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>
till date: 27-06-2022
using package: https://pub.dev/packages/url_launcher
dependencies - url_launcher: ^6.1.2
TextButton(
onPressed: () {
_launchWhatsapp();
},
)
_launchWhatsapp() async {
var whatsapp = "+91XXXXXXXXXX";
var whatsappAndroid =Uri.parse("whatsapp://send?phone=$whatsapp&text=hello");
if (await canLaunchUrl(whatsappAndroid)) {
await launchUrl(whatsappAndroid);
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("WhatsApp is not installed on the device"),
),
);
}
}
Here is new update way...
whatsapp() async{
var contact = "+880123232333";
var androidUrl = "whatsapp://send?phone=$contact&text=Hi, I need some help";
var iosUrl = "https://wa.me/$contact?text=${Uri.parse('Hi, I need some help')}";
try{
if(Platform.isIOS){
await launchUrl(Uri.parse(iosUrl));
}
else{
await launchUrl(Uri.parse(androidUrl));
}
} on Exception{
EasyLoading.showError('WhatsApp is not installed.');
}
}
and call whatsapp function in onpress or ontap function
For using the wa.me domain, make sure to use this format...
https://wa.me/123?text=Your Message here
This will send to the phone number 123. Otherwise, you will get an error message (see? https://wa.me/?text=YourMessageHere ). Or, if you don't want to include the phone number, try this...
https://api.whatsapp.com/send?text=Hello there!
Remember, wa.me requires a phone number, whereas api.whatsapp.com does not. Hope this helps!
I know it is too late for answering this, but for those who want the same functionality, the current way is to do it like this:
launchUrl(Uri.parse('https://wa.me/$countryCode$contactNo?text=Hi'),
mode: LaunchMode.externalApplication);
if you will use URL Launcher then the whatsapp link will be open on web browser. So you need to set parameter - not to open on safari browser. The complete code you can find on this flutter tutorial.
But for your case use below code.
await launch(whatappURL, forceSafariVC: false);
Today i am adding solution its working fine on my desktop and phone
Add 91 if your country code is +91
Remember not add any http or https prefix otherwise wont work.
whatsapp://send?phone=9112345678&text=Hello%20World!

FILE_URI path for Camera not working on IONIC 4

When using the Cameara to take a picture with destinationType: this.camera.DestinationType.FILE_URI, the resulting URL will not work to display the image. For example, when attempting to take a photo like this:
this.camera.getPicture(options).then((url) => {
// Load Image
this.imagePath = url;
}, (err) => {
console.log(err);
});
Attempting to display it as <img [src]="imagePath" > will result in an error (file not found).
The problem here is that the URL is in the file:///storage... path instead of the correct one based on localhost.
In previous versions of Ionic, this would be solved by using normalizeURL. This will not work on Ionic 4 (or at least I could not make it work).
To solve this issue, you will need to use convertFileSrc():
import {WebView} from '#ionic-native/ionic-webview/ngx';
...
this.camera.getPicture(options).then((url) => {
// Load Image
this.imagePath = this.webview.convertFileSrc(url);
}, (err) => {
console.log(err);
});
Now the image URL will be in the appropriate http://localhost:8080/_file_/storage... format and will load correctly.
See WKWebView - Ionic Docs for more information.
In my case, the following code works with me
const downloadFileURL = 'file:///...';
// Convert a `file://` URL to a URL that is compatible with the local web server in the Web View plugin.
const displayedImg = (<any>window).Ionic.WebView.convertFileSrc(downloadFileURL);
In case some gots here looking for the answer on ionic4, check this out
"Not allowed to load local resource" for Local image from Remote page in PhoneGap Build
and look for the answer from #Alok Singh that's how I got it working on ionic4 and even works with livereload
UPDATE december 2021:
You have to install the new Ionic Webview
RUN:
ionic cordova plugin add cordova-plugin-ionic-webview
npm install #awesome-cordova-plugins/ionic-webview
Import it in app.module and your page where you wanna use it:
import { WebView } from '#awesome-cordova-plugins/ionic-webview/ngx';
image = "";
constructor(private webview: WebView){}
Then this will work:
this.camera.getPicture(options).then((imageData) => {
this.image = this.webview.convertFileSrc(imageData)
}, (err) => {
// Handle error
});
And show it in the HTML page:
<img [src]="image" alt="">

How do I embed a Facebook Feed in the new Google Sites (using Apps Script)?

I've read that you can make a Google Apps Script that shows a Facebook Feed, and then embed this in a Google Site, but I can't find any more information on how to do it and I can't figure it out myself.
When I try to make an Apps Script web app with a Facebook feed I get errors like:
Uncaught DOMException: Failed to set the 'domain' property on 'Document': Assignment is forbidden for sandboxed iframes.
This is from copying the "Facebook Javascript SDK" and "Page Feed" from Facebook Developers into an HTML file and deploying it as a web app. I gather it has something to do with how Apps Script sandboxes your code but I don't know what I have to do here.
For that matter, even if I try to make a simpler Apps Script with some static HTML, when I try to embed it from Drive into the site I get an error "Some of the selected items could not be embedded".
The New Google Sites doesn't support Google Apps Script.
Related question: Google App Scripts For New Google Sites Release
The new Google Sites does now support embedding apps script (make sure to deploy the apps script as a web app, set the right permissions, and use the /exec url and not your /dev one to embed).
I found I couldn't use the facebook SDK for videos because of the sandboxing. I used an iframe solution instead for videos, but maybe you could try something like this for the feed (I'm assuming you've registered your app in fb so you can get generate tokens):
In apps script, create a .gs file and an html file, roughly along the lines below (I haven't actually worked with returning feeds, so check the returned data structure and adjust accordingly)
//**feed.gs**
function doGet(e) {
return HtmlService
.createTemplateFromFile('my-html-file')
.evaluate();
}
function getToken() { //use your fb app info here (and make sure this script is protected / runs as you
var url = 'https://graph.facebook.com'
+ '/oauth/access_token'
+ '?client_id=0000000000000000'
+ '&client_secret=0x0x0x0x0x0x0x0x0x0x0x0x'
+ '&grant_type=client_credentials';
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = response.getContentText();
var jsondata = JSON.parse(json);
return jsondata.access_token;
}
function getFeed() {
var url = 'https://graph.facebook.com'
+ '/your-page/feed'
+ '?access_token=' + encodeURIComponent(getToken());
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = response.getContentText();
var jsondata = JSON.parse(json);
//Logger.log(jsondata); //check this and adjust following for loop and html showFeed function accordingly
var posts = {};
for (var i in jsondata) {
posts[i] = {"post":jsondata[i].message};
}
return posts;
}
<!--**my-html-file.html**-->
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
// The code in this function runs when the page is loaded (asynchronous).
$(function() {
google.script.run
.withSuccessHandler(showFeed)
.withFailureHandler(onFailure)
.getFeed(); //this function is back in .gs file and must return an array or object which gets auto-passed to the showFeed function below
});
function showFeed(posts) { //parameter name must match array or object returned by getFeed in gs file
var html = '';
for (var p in posts) {
html += '<p>' + posts[p].post + '</p>'; //instead of a string, you can build an array for speed
}
$('#feed').empty().append(html); //if you used an array for the html, you'd split it here
}
function onFailure(error) {
$('#feed').empty().append("Unable to retrieve feed: " + error.message); ;
}
</script>
</head>
<body>
<div id="feed">
Loading...
</div>
</body>
</html>

Unexpected behavior for Facebook Sharing [duplicate]

This question already has an answer here:
Facebook ignoring OG image on first share
(1 answer)
Closed 6 years ago.
First of all hi and thanks in advance to anyone who can help with this because I've been going crazy over this for weeks now.
So I've got a website which lists gif taken from my mobile application (which are then stored on AWS and my visitors ( I haven't found a use for me to have users) can share these gifs on facebook using the facebook sdk.
The problem appears when I try sharing an image for the first time
This is what the share dialog shows the first time I click on my sharing button:
http://i.stack.imgur.com/lNVNF.png
and then I close and reclick the same button and now it works:
http://i.stack.imgur.com/YsDUm.png
Now I've been trying to find a way to make this work on the first sharing attempt but to no avail.
I am using meteor in combination with biasport:facebook-sdk and Amazon S3 for the hosting of my files.
Edit here is the code used:
FRONT SIDE
HTML
<div class="facebook share">
<img src="/gallery/fb.png">
</div>
Javascript
Template.*templateName*.events({
'click .facebook': function(e){
e.preventDefault();
e.stopPropagation();
// this is in a modal so I store the data I need
// (events have photos which in turn contain a url to the gif
var url = Session.get('event').photos[Session.get("id")].url;
FB.ui({
method: 'share',
href: url
});
}
SERVER SIDE
JAVASCRIPT
if(Meteor.isClient) {
window.fbAsyncInit = function() {
FB.init({
appId : 'APP_ID',
status : true,
xfbml : true,
version : 'v2.5'
});
};
}
Edit: I found a manual solution using exec future and curl
so first I added a call to a meteor method on the share that updates the facebook crawler
JAVASCRIPT
Template.*templateName*.events({
'click .facebook': function(e){
e.preventDefault();
e.stopPropagation();
// this is in a modal so I store the data I need
// (events have photos which in turn contain a url to the gif
var url = Session.get('event').photos[Session.get("id")].url;
Meteor.call('updateCrawler', url, function(){
FB.ui({
method: 'share',
href: url
});
});
}
Then I defined my meteor method as such
JAVASCRIPT
Meteor.methods({
updateCrawler: function(url){
var future = new Future();
cmd = 'curl -X POST -F "id=' + url + '" -F "scrape=true" -F "access_token={my_access_token}" "https://graph.facebook.com"';
exec(cmd, function(error){
if (error){
console.log(error);
}
future.return();
});
future.wait();
}
});
it's ugly but since I'd have to wait for the crawler to update and it works I'll leave this here for future use for someone maybe
Edit2:
I did not use og tags at all since I was simply sharing a url to aws directly and not a url to my website
I worked around this problem by calling the Facebook API direct from the server to make it scrape the og data by requesting info on the page. First time round it doesn't have the image cached but second time it does so this workaround does the initial call before sharing.
Use an access token for your facebook app and call the below in an ajax call and await the response before opening share dialog. Replace Google address with your own uri encoded address https://graph.facebook.com/v2.5/?id=http%3A%2F%2Fwww.google.co.uk&access_token=xxxxx
EDIT:
As per comments, here is my server side method for calling this which I use when posts etc are inserted to make the initial call and prompt a scrape from fb:
var getTheOGInfo = function (link)
{
if (!link || link.slice(0, 4).toLowerCase() != "http"){
throw new Meteor.Error("og-info-bad-url", "Function requires an unencoded fully qualified url");
return false;
}
var url = "https://graph.facebook.com/v2.5/{{{{id}}}}?access_token={{{{token}}}}&fields=og_object{id,description,title,type,updated_time,url,image},id,share";
var token = Meteor.settings.private.fb.token;
if (!token){
throw new Meteor.Error("og-info-no-token", "Function requires a facebook token in Meteor.settings.private.fb.token");
return false;
}
var link_id = encodeURIComponent(link);
url = url.replace('{{{{token}}}}', token).replace('{{{{id}}}}', link_id);
var result = HTTP.get(url, {timeout:1000});
return result;
}
Or for your purposes you may not want anything that might be blocking so you could change the last two lines to be aynchronous:
var result = HTTP.get(url, {timeout:1000});
return result;
//Replace with non blocking
HTTP.get(url, {timeout:1000}, function(err, result){console.log('something asynchronous', err, result);});
return true;