I had been trying to open/navigate App Store from my application when there is a version upgrade.
For that I have written customrender which works perfectly fine for android. But it's not working for iOS. Following is the code written for iOS customrenderer. I attached the screenshot of the code in an attachment.
public class OpenAppStore : UIViewController, ISKStoreProductViewControllerDelegate, IOpenStore
{
public void OpenStore()
{
bool isSimulator = Runtime.Arch == Arch.SIMULATOR;
if (!isSimulator)
{
var storeViewController = new SKStoreProductViewController();
storeViewController.Delegate = this;
var id = SKStoreProductParameterKey.ITunesItemIdentifier;
var productDictionaryKeys = new NSDictionary("SKStoreProductParameterITunesItemIdentifier", 1389696261);
var parameters = new StoreProductParameters(productDictionaryKeys);
storeViewController.LoadProduct(parameters, (bool loaded, NSError error) =>
{
if ((error == null) && loaded)
{
this.PresentViewController(storeViewController, true, () =>
{
Console.WriteLine("SKStoreProductViewController Completed");
});
}
if (error != null)
{
throw new NSErrorException(error);
}
});
}
else
{
var itunesLink = new NSUrl("https://itunes.apple.com/us/genre/ios/id36?mt=8");
UIApplication.SharedApplication.OpenUrl(itunesLink, new NSDictionary() { }, null);
}
}
}
Problem : It doesn't throw any error. PresentViewController is called but it doesn't navigate/open my app in the App Store.
Thank you
Firstly, you don't need a custom renderer for this. You should inject a simple helper class that will open the appropriate app store for each platform you support.
Secondly, the url you are using for the iOS App Store looks to be incorrect. Use something like:
var url = new NSUrl($"https://itunes.apple.com/us/app/apple-store/{myAppId}?mt=8");
The app store URL used above is from the Apple docs. You can then open that url.
Related
I'm writing a unit test to check some methods operating on the files. I've used System.IO.Abstraction on the library side, and System.IO.Abstraction.UnitTesting on the UnitTests side.
I'm using MacOS, but I want to be able to run tests on the Windows too. The problem is around paths because as we know on windows it's like "C:\MyDir\MyFile.pdf", but for Linux/MacOS it's more like "/c/MyDir/MyFile.pdf".
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ #"/c/scans/myfile.pdf", new MockFileData("Some text") },
{ #"/c/scans/mysecondfile.pdf", new MockFileData("Some text") },
{ #"/c/scans/mydog.jpg", new MockFileData("Some text") }
});
var fileService = new FileService(fileSystem);
var scanDirPath = #"/c/scans/";
I don't know exactly how to deal with this thing. I'm wondering about setting the "initial" path in the constructor of the xunit tests depending on the platform, but I'm not sure if it's a good practice.
I encountered the same scenario where I needed to execute a unit test with the System.IO.Abstraction.TestingHelpers's MockFileSystem on both Windows and Linux. I got it working by adding a check for the platform and then using the expected string format for that platform.
Following the same logic, your tests might look like this:
[Theory]
[InlineData(#"c:\scans\myfile.pdf", #"/c/scans/myfile.pdf")]
[InlineData(#"c:\scans\mysecondfile.pdf", #"/c/scans/mysecondfile.pdf")]
[InlineData(#"c:\scans\mydog.jpg", #"/c/scans/mydog.jpg")]
public void TestName(string windowsFilepath, string macFilepath)
{
// Requires a using statement for System.Runtime.InteropServices;
bool isExecutingOnWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
bool isExecutingOnMacOS = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
MockFileSystem fileSystem;
if (isExecutingOnWindows)
{
fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ windowsFilepath, new MockFileData("Some text") }
};
}
else if (isExecutingOnMacOS)
{
fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ macFilepath, new MockFileData("Some text") }
};
}
else
{
// Throw an exception or handle this however you choose
}
var fileService = new FileService(fileSystem);
// Test logic...
}
I implemented App.Metrics into my wcf application (App.Metrics ver 3.1.0).
When I check url in which data is uploaded I found that app isn't filled:
Tried to figured out reason of this behavior I found manual:
https://www.app-metrics.io/getting-started/fundamentals/tagging-organizing/
It said that AssemblyName needs to be filled, but I double-checked it - csproj file contain next row:
<AssemblyName>MyWebService</AssemblyName>
How can I fill this app property in metrics?
startup.cs:
var metrics = MetricsProvider.Instance.Metrics;
SetMetricsAppTag(metrics, Assembly.GetExecutingAssembly().GetName().Name);
private static void SetMetricsAppTag(IMetricsRoot metricsRoot, string appTagValue)
{
if (!metricsRoot.Options.GlobalTags.ContainsKey("app"))
{
metricsRoot.Options.GlobalTags.Add("app", appTagValue);
}
else if (string.IsNullOrEmpty(metricsRoot.Options.GlobalTags["app"]) || metricsRoot.Options.GlobalTags["app"] == "unknown")
{
metricsRoot.Options.GlobalTags["app"] = appTagValue;
}
}
a better way will be to do in startup-
var metrics = AppMetrics.CreateDefaultBuilder().
Configuration.
Configure(options => options.AddAppTag(appName: "nexus"))
.Build();
services.AddMetrics(metrics);
services.AddMetricsTrackingMiddleware();
services.AddMetricsEndpoints(opt =>
{
opt.MetricsTextEndpointOutputFormatter = new MetricsPrometheusTextOutputFormatter();
opt.MetricsEndpointOutputFormatter = new MetricsPrometheusProtobufOutputFormatter();
opt.EnvironmentInfoEndpointEnabled = false;
});
I'm trying to implement Keychain from start to finish for my Xamarin Application. At the moment I have the initial bit that will display the native prompt `Touch ID to Use Password'. That works successfully using the bit of code below.
public class TouchId : ITouchID
{
public Task<bool> AuthenticateUserIDWithTouchID()
{
var taskSource = new TaskCompletionSource<bool>();
var context = new LAContext();
if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out NSError AuthError))
{
var replyHandler = new LAContextReplyHandler((success, error) => {
taskSource.SetResult(success);
});
context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, "Logging with touch ID", replyHandler);
};
return taskSource.Task;
}
}
My question is how do I display the native prompt asking if I would like to save to Keychain.
I've created a basic one using xamarin's Display Alert, but it doesn't quite look as nice as the native.
Xamarin documentation is a mess all over the internet but I cannot seem to find a solid example of how to handle my Xamarin.Forms application being launched from a notification or handling a notification being clicked while my application is already running.
So I am inside of the Xamarin.Forms.UWP application in the App.xaml.cs file that handles all the UWP launching. Within the OnActivated method I can see that my application receives a fire and gets the proper data from my toast notification. My question is how do I pass that data back into the Xamarin.Forms instance.
protected override void OnActivated(IActivatedEventArgs args)
{
base.OnActivated(args);
var _args = (args as LaunchActivatedEventArgs).Arguments;
}
Custom UWP Notification Service:
ToastContent content = new ToastContent()
{
Launch = "...",
Visual = new ToastVisual()
{
BindingGeneric = new ToastBindingGeneric()
{
Children =
{
new AdaptiveText()
{
Text = title,
HintMaxLines = 1
},
new AdaptiveText()
{
Text = body
}
}
}
},
Actions = new ToastActionsCustom()
{
Buttons =
{
new ToastButton(acceptAction.Key, $"action={acceptAction.Value}")
{
ActivationType = ToastActivationType.Foreground
},
new ToastButton(declineAction.Key, $"action={declineAction.Value}")
{
ActivationType = ToastActivationType.Background
}
}
}
};
var toast = new ToastNotification(content.GetXml());
ToastNotificationManager.CreateToastNotifier().Show(toast);
How do I go about sending this _args variable back into the running instance of my cross-platform application so that I can process the logic of navigating to a route, etc.
Furthermore if I have to write some custom code to handle this I will want the code to be easy to integrate the same functionally with the Xamarin.Forms.Android app in this project as well.
I was searching for the Xamarin implementation of How to open settings programmatically
Vito-ziv answered it for objective C - what is the correct way to do this in C# for iOS in Xamarin Studio?
For current devices this is only possible in ios8 (ios9 not available at time of writing) (It used to be possible before ios5 apparently - see this blog post from Adrian Stevens at Xamarin - shout out to him for the inspiration for this answer)
To do it in ios8, I did it like this:
var settingsString = UIKit.UIApplication.OpenSettingsUrlString;
var url = new NSUrl (settingsString);
UIApplication.SharedApplication.OpenUrl (url);
Where the above code was called from a click event via delegate class in a UIAlertView click.
Since I am supporting ios7 too, to handle ios7 devices I did this, where the HandleLocationAuthorisation method is called when deciding whether to present a view controller - the user on ios8 and above can choose to go to the settings directly, whereas the user on ios7 has to go there manually.
This example below is checking for location services, but with trivial changes could easily be changed to check for other types of settings.
public bool HandleLocationAuthorisation ()
{
if (CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways) {
return true;
} else {
UIAlertView uiAlert;
//iOS 8 and above can redirect to settings from within the app
if (UIDevice.CurrentDevice.CheckSystemVersion(8,0)) {
uiAlert = new UIAlertView
("Location Services Required",
"",
null,
"Return To App","Open Settings");
uiAlert.Delegate = new OpenSettingsFromUiAlertViewDelegate();
uiAlert.Message = "Authorisation to use your location is required to use this feature of the app.";
//ios7 and below has to go there manually
} else {
uiAlert = new UIAlertView
("Location Services Required",
"Authorisation to use your location is required to use this feature of the app. To use this feature please go to the settings app and enable location services",
null,
"Ok");
}
uiAlert.Show ();
return false;
}
}
For completeness, here is the code for the event delgate referenced above:
public class OpenSettingsFromUiAlertViewDelegate : UIAlertViewDelegate {
public override void Clicked (UIAlertView alertview, nint buttonIndex)
{
if (buttonIndex == 1) {
var settingsString = UIKit.UIApplication.OpenSettingsUrlString;
var url = new NSUrl (settingsString);
UIApplication.SharedApplication.OpenUrl (url);
}
}
}
Hope this will help you. This is working in iPhone not sure about working on iPad.
var url = new NSUrl("prefs:root=Settings");
UIApplication.SharedApplication.OpenUrl(url);