How can I open a URL in the device's default browser and also change the view of the app so after they are done looking at the opened URL and they go back to the app, they are in a new view?
Below is what I have so far:
Button btnOkay = FindViewById<Button>(Application.Context.Resources.GetIdentifier("btnOkay", "id", Application.Context.PackageName));
btnOkay.Click += (sender, eventArgs) =>
{
// Open Survey Monkey Survey in Browser
var uri = Android.Net.Uri.Parse("https://www.example.com/");
var intent = new Intent(Intent.ActionView, uri);
StartActivity(intent);
// Go to Thank you view in app.
intent = new Intent(this, typeof(PatientPostVisitSurveyThanksActivity));
StartActivity(intent);
};
The issue with this is, it goes to the next view, and will only open the URL in the browser if I click back to go to the original view.
I just want the app view to be changed when the user manually goes back into the app.
You can use the Activity lifecycles for this. Your app's last Activity will execute OnResume after the user press back (or selects it from the active app list). Set a flag before launching the browser and test for that flag in the OnResume
btnOkay.Click += (sender, eventArgs) =>
{
GotoNewActivity = true;
// Open Survey Monkey Survey in Browser
var uri = Android.Net.Uri.Parse("https://www.example.com/");
var intent = new Intent(Intent.ActionView, uri);
StartActivity(intent);
};
bool GotoNewActivity;
protected override void OnResume()
{
base.OnResume();
if (GotoNewActivity)
{
GotoNewActivity = false;
// Go to Thank you view in app.
var intent = new Intent(this, typeof(ThankYouActivity));
StartActivity(intent);
}
}
Related
I'm trying to have the default web browser open up an URL that is provided by the user in this case let's say it's https://stackoverflow.com/ but when the program runs the app is returning true for the LaunchUriAsync, but it isn't opening the browser and navigating to the site. How would I get a browser to open up the URL?
private void Button_Click(object sender, RoutedEventArgs e)
{
string url = StoreUrl.Text;
Uri uri = new Uri(#"" + url);
DefaultLaunch(uri);
}
async void DefaultLaunch(Uri uri)
{
// Launch the URI
var success = await Windows.System.Launcher.LaunchUriAsync(uri);
if (success)
{
// URI launched
}
else
{
// URI launch failed
}
}
I just created a new project and pasted the following code into the Loaded event
var success = await Windows.System.Launcher.LaunchUriAsync(new Uri("https://stackoverflow.com/"));
It worked fine for me.
If the call returns true, there seemingly nothing to stop this from working. At this stage I would suggest this is an environmental issue, or something do with the shell mechanism of that browser.
From here I would
Test this in a new clean project.
Change the default browser, if this works then there is likely some sort of setting/corruption within the browser
Disable your antivirus and see if it works.
I want to redirect my user from email link to a particular app page.
I do not have a subsequent website, my app is independent.
I have tried intent filters and it does take me to the apps main activity but how do i navigate the user to particular activity is my main roadblock.
Am not interested in app linking I just require deep linking.
I want to know how to to navigate to the particular activity from the link itself directly.
I have tried intent filters in mainactivity.cs along with datascheme.
In my implementation when i send an link inside the email and i click OS asks me how should I proceed
1.By app or 2. Chrome This is fine.
But when i click on app it opens from the main activity.
[IntentFilter(new[] { Android.Content.Intent.ActionView },
AutoVerify = true,
Categories = new[]
{
Android.Content.Intent.CategoryDefault,
Android.Content.Intent.CategoryBrowsable
},
DataScheme = "http",
DataPathPrefix = "",
DataHost = "MyAppName")]
Suppose the url you click is http://myappname?destination=a, you can get the data in activity through:
if (Intent.Data != null)
{
var host = Intent.Data.EncodedAuthority;
var parameter = Intent.Data.GetQueryParameter("destination");
}
As you are using Xamarin.Forms, you should navigate to the specify page on Forms. MessagingCenter is a good choice.
Firstly, register it in App on Forms project:
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
MessagingCenter.Subscribe<object, object>(this, "Navigate", (sender, args) =>
{
if ((string)args == "a")
{
MainPage = new SecondPage();
// or (MainPage as NavigationPage).PushAsync(new SecondPage());
}
});
}
Fire this messaging center when you recieve the data:
if (host == "myappname")
{
MessagingCenter.Send<object, object>(this, "Navigate", parameter);
}
Update
If you don't want to use MessagingCenter. Define a public method in App like:
public void MoveToPage(string pageName)
{
if (pageName == "a")
{
MainPage = new SecondPage();
// or (MainPage as NavigationPage).PushAsync(new SecondPage());
}
}
Then call this when Intent.Data != null in MainActivity:
var formsApp = new App();
LoadApplication(formsApp);
if (Intent.Data != null)
{
var host = Intent.Data.EncodedAuthority;
var parameter = Intent.Data.GetQueryParameter("destination");
formsApp.MovePage(parameter);
}
Converting the code in the following swift sample to C# (Xamarin) to notify the App when Paypal Token is received inside SFSafariViewController but it does not fire the method.
https://github.com/paypal/paypal-here-sdk-ios-distribution/blob/master/SampleApp/PPHSDKSampleApp/InitializeViewController.swift
Converted the swift to C# as following but after user login to PayPal and receives the token, Safari is not closing to fire SetupMerchant()
UrlSchemes is also set to retailsdksampleapp to match the sample swift app from PayPal.
SafariDelegate safariDelegate = new SafariDelegate(this);
NSNotificationCenter.DefaultCenter.AddObserver(new NSString("kCloseSafariViewControllerNotification"), safariDelegate.SetupMerchant);
void loadBrowser()
{
var url = new NSUrl("https://paypalauth.herokuapp.com/toPayPal/" + Application.paypalEnvironment + "?returnTokenOnQueryString=true");
var svc = new SFSafariViewController(url);
svc.Delegate = safariDelegate;
this.PresentViewController(svc, true, null);
}
public class SafariDelegate : SFSafariViewControllerDelegate
{
ViewController _controller = null;
public SafariDelegate(ViewController controller)
{
_controller = controller;
}
public void SetupMerchant(NSNotification notification)
{
// Dismiss the SFSafariViewController when the notification of token has been received.
this._controller.PresentedViewController?.DismissViewController(true, () => { });
// Grab the token(s) from the notification and pass it into the merchant initialize call to set up
// the merchant. Upon successful initialization, the 'Connect Card Reader' button will be
// enabled for use.
var accessToken = notification.Object.ToString();
}
}
When running the swift sample app from Paypal, it closes the browser (SFSafariViewController) after login and fires the SetupMerchant() but not in the C# code. There is possibly a missing step or invalid code conversion.
If the Safari controller is not closing and you have the proper UrlScheme set (), then you are missing the OpenUrl override in your AppDelegate class that listening for your app's url schemes and posts the notification that your view controller is listening for.
Example:
[Export("application:openURL:sourceApplication:annotation:")]
public bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
if (sourceApplication == "com.apple.SafariViewService")
{
var dict = HttpUtility.ParseQueryString(url.Query);
var token = dict["access_token"];
NSNotificationCenter.DefaultCenter.PostNotificationName("kCloseSafariViewControllerNotification", new NSString(token));
};
return true;
}
I am creating a UWP app using c#. The app is supposed to fetch information from a website and present it to the user. I've went through the DOM of the site and managed to download the HTML of the site. But some of the information is hidden and only appears when certain buttons or selections are made on the website. Is there a way that I can programmatically go into the site, make a selection, the download the new html?
2nd Question: The app should have an fb liveChat function linked an fb page. How do I link facebook liveChat into this app? I do not have an idea in my head on how to make this work. Thank you for you help.
Here is an example for Entering text in search box and Click search button in Bing
Use WebView to do all the work
WebView webView = new WebView();
Use InvokeScriptAsync method for WebView to use JS code
webView.InvokeScriptAsync("eval", new string[] {});
Get the HTML of the site using below code
public LoadURI()
{
webView.Navigate(new Uri("https://www.bing.com/"));
webView.NavigationCompleted += webView_NavigationCompletedAsync;
}
string siteHtML = null;
private async void webView_NavigationCompletedAsync(WebView sender, WebViewNavigationCompletedEventArgs args)
{
siteHtML = await webView.InvokeScriptAsync("eval", new string[] { "document.documentElement.outerHTML;" });
}
Enter text in search box using below code
private async void EnterTextAsync(string enterText)
{
var functionString = string.Format(#"document.getElementsByClassName('b_searchbox')[0].innerText = '{0}';", enterText);
await webView.InvokeScriptAsync("eval", new string[] { functionString });
}
Simulate click using below code
private async void SimulateClickAsync()
{
var functionString = string.Format(#"ddocument.getElementsByClassName('b_searchboxSubmit')[0].click();");
await webView.InvokeScriptAsync("eval", new string[] { functionString });
}
Get new site's HTML using Step 3
Here is a Sample app for LogIn to StackOverflow: StackOverFlow-LogIn
I'm building an application for WP7 using the Facebook C# SDK. When I attempt to post a message to a users wall (Just a plain message) everything works fine. But when I attempt to post a link to the users wall I get this exception message:
(OAuthException) (#100) The post's links must direct to the application's connect or canvas URL.
Does anyone know how to fix this? I have heard of canvas applications but I didn't think this applied to a phone app. Perhaps this is a setting on Facebook?
Any feedback is appreciated.
Here is the code I used to post to facebook:
private void button1_Click(object sender, RoutedEventArgs e)
{
_fbClient.PostCompleted +=
(o, er) =>
{
if (er.Error == null)
{
MessageBox.Show("Success");
}
else
{
MessageBox.Show(er.Error.Message);
}
};
var args = new Dictionary<string, object>();
args["name"] = "Hello World!!";
args["link"] = "http://www.nfl.com";
args["caption"] = "";
args["description"] = "";
args["picture"] = "";
args["message"] = "Hello World from application.";
args["actions"] = "";
FacebookAsyncCallback callback = new FacebookAsyncCallback(this.postResult);
_fbClient.PostAsync("me/feed", args, callback);
}
private void postResult(FacebookAsyncResult asynchResult)
{
MessageBox.Show("Success");
}
NOTE: If I remove the string from "link" it works.
I found a solution to my problem "here". In your app settings within Facebook you have to set "Stream Post Url Security" to false. Hope this helps someone.
Go to the Facebook App. Edit its settings. On the Advanced settings page, disable the "Stream post URL security" option.