Xamarin.Forms (iOS) Requesting tracking Authorization in release will not prompt the user but assume the user clicked denied - ios

As of the newest iOS polices, you have the ask the user if you can track him or her. In debug, the below code will open a prompt asking the user wether he or she is ok with being tracked. If given the ok, the app continues, if denied the app ends (after the iMessage).
However, as soon as I put the app into release and deploy it to a real phone, the prompt is always skipped and instead the fail iMessage is shown and the app exits.
Why is the prompt missing on production? In debug, it works totally fine.
if (Device.RuntimePlatform == Device.iOS)
{
try
{
ATTrackingManager.RequestTrackingAuthorization((status) => {
if (status == ATTrackingManagerAuthorizationStatus.Authorized)
{
//start once at launch afterwards with timer
GetNewChatsCount();
SetButtons();
StartChatDownloadCounter();
}
else if (status == ATTrackingManagerAuthorizationStatus.Denied)
{
Device.BeginInvokeOnMainThread(async() =>
{
DependencyService.Get<IMessage>().VeryLongAlert("Leider kannst du in diesem Fall die App nicht nutzen. Wir benötigen diese Infos, um allen Kunden ein gesichertes Umfeld zu bieten. Installiere die App neu, wenn du deine Meinung änderst.");
await Task.Delay(8000);
Environment.Exit(0);
});
}
});
}
catch (Exception e)
{
}
}

Related

How to resolve the location permission error for Apps on Huawei device?

Huawei HMS core on my huawei phone do not have defualt permission, I am coding my app using HMS location kit and always got a permission error for Location kit. I followed their development guide to set up the location permission in the Manifest file.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
And followed their code samples:
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
Log.i(TAG, "sdk < 28 Q");
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] strings =
{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
ActivityCompat.requestPermissions(this, strings, 1);
}
} else {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this,
"android.permission.ACCESS_BACKGROUND_LOCATION") != PackageManager.PERMISSION_GRANTED) {
String[] strings = {android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION,
"android.permission.ACCESS_BACKGROUND_LOCATION"};
ActivityCompat.requestPermissions(this, strings, 2);
}
}
Any advice?
The HMS permission must always be allowed. Otherwise, an error will be reported.
Ensure that the location permission has been assigned to HMS Core (APK). To do so, go to Settings > Apps > Apps and find HMS Core. (The menu path may vary depending on the operating system version. If HMS Core is not found, tap the menu icon in the upper right corner of Apps and tap Show system processes.) Then, tap the HMS Core (APK) icon, go to App info > Permissions > Location, and verify that the location permission is assigned to HMS Core. On a device running EMUI 10.0 or later, Location must be set to Always for HMS Core.
Ensure that the Location Info switch in the drop-down notification bar is turned on.
Simulate Location Requires Impersonation Permission. Otherwise, an error permission error will be reported.
Check whether Location Permission is enabled for your app.
Shirley's answer covers the device side of HMS location permission. To cover this type of scenario for all users with lower EMUI versions that HMS Core does not have location permissions by default, you can use the API "settingsClient.checkLocationSettings(…)" to obtain the device location permission. After that, even the location permission for the HMS Core App was disabled, your app will be able to prompt users to enable related permissions with one-click.
Please refer to HMS Location guide
Step 1: Obtain the service API of SettingsClient.
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
Step 2: Call checkLocationSettings() to check the device settings.
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
mLocationRequest = new LocationRequest();
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
//check Location Settings
settingsClient.checkLocationSettings(locationSettingsRequest)
.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
//Have permissions, send requests
fusedLocationProviderClient
.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//Interface call successfully processed
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception e) {
//Settings do not meet targeting criteria
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
ResolvableApiException rae = (ResolvableApiException) e;
//Calling startResolutionForResult can pop up a window to prompt the user to open the corresponding permissions
rae.startResolutionForResult(MainActivity.this, 0);
} catch (IntentSender.SendIntentException sie) {
//…
}
break;
}
}
});

About Xamarin Camera permission

I'm making Android app with Xamarin, This use zxing.
When user click a button, It show QrScan page and dialog for asking allow camera permission.
I want to show dialog asking permission by user allow permission every time clicked button.
Now, If user click deny, permission dialog ever don't shown, before restart application.
Have you any idea?
This is my source.
Android --- MainActivity.cs
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
ZXing.Net.Mobile.Forms.Android.Platform.Init();
LoadApplication(new App { OSVersion = "Android Version " + "2.0" });
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
// If this is not be, occur unexpected exception when user click deny
if(grantResults[0] == Permission.Denied)
{
return;
}
global::ZXing.Net.Mobile.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
And this is my Executing QrScan Method In PCL project which called clicked button.
public async void ImgQrScan_Clicked(object sender, EventArgs e)
{
this.TappedEvent?.Invoke(sender, e);
CustomScanViewMaker();
await Navigation.PushModalAsync(oCustomQrScanPage);
zxingPage.IsScanning = true;
string sScanResult = "";
zxingPage.OnScanResult += (result) =>
{
sScanResult = result.Text;
zxingPage.IsScanning = false;
Device.BeginInvokeOnMainThread(async () =>
{
this.OnClicked?.Invoke(sender, new QrScannerClickEventArgs(sScanResult));
await Navigation.PopModalAsync();
});
};
this.OnClicked?.Invoke(sender, new QrScannerClickEventArgs(sScanResult));
}
Thank you.
I want to show dialog asking permission by user allow permission every time clicked button.
You could try using shouldShowRequestPermissionRationale method to implement this feature, as the document said :
To help find situations where the user might need an explanation, Android provides a utiltity method, shouldShowRequestPermissionRationale(). This method returns true if the app has requested this permission previously and the user denied the request.
For its usage, you could refer to the official document Requesting Permissions at Run Time, in C#, it's something like this :
// Here, this is the current activity
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.Camera) != Permission.Granted)
{
// Should we show an explanation?
if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.Camera))
{
// Provide an additional rationale to the user if the permission was not granted
// and the user would benefit from additional context for the use of the permission.
// For example if the user has previously denied the permission.
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
Log.Info(TAG, "Displaying camera permission rationale to provide additional context.");
}
else
{
// No explanation needed, we can request the permission.
ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.Camera }, REQUEST_CAMERA);
// REQUEST_CAMERA is an app-defined int constant. The callback method gets the
// result of the request.
}
}
else
{
System.Diagnostics.Debug.WriteLine("Permission Granted!!!");
}

Xamarin Forms does not wait for GeoLocation approval on iOS

I am have Xamarin Forms cross platform application for iOS, Android and UWP. I use the Xam.Plugin.Geolocator to get the location from each of the devices. My challenge with iOS is on the first launch of the app on a device. My code runs through and detects that IsGeolocationEnabled for the Plugin.Geolocator.Abstractions.IGeolocator object is false before the use is ever presented with the option to allow the application to use the device's location. This causes my app to inform the user that Location Services are not enabled for the application.
Basically I am hitting the line of code below before the use is ever asked about location services:
if (!App.gobj_RealGeoCoordinator.IsGeolocationEnabled)
ls_ErrorMessage = resourcestrings.GetValue("NoLocationServicesMessage");
On the other platforms, UWP at least, it seems that the app is paused while waiting for the user to respond to the request to use location services. Android just seems to automatically allow access to location if an app uses it.
Any idea how I can have the iOS detect if the request to use location services has been answered or not on the first run? Any suggestions would be greatly appreciated.
UPDATE(1):
I have all the correct items in my info.plist as seen below. I do eventually get the request to use the location just after my app has already checked IsGeolocationEnabled and decided the user has not enabled location services for the app.
UPDATE (2):
So I made a little progress using the following code.
try
{
while (!App.gobj_RealGeoCoordinator.IsGeolocationEnabled)
{
await Task.Delay(1000);
}
ViewModelObjects.AppSettings.CanAccessLocation = App.gobj_RealGeoCoordinator.IsGeolocationEnabled;
}
catch (Exception ex)
{
XXXXXXX
}
The challenge is that the plugin appears to provide me no way of knowing in the user has not responded to the location services dialog (i.e. IsGeolocationEnabled == false) versus the user said no to the location services dialog (also IsGeolocationEnabled == false). Any suggestions?
The way this type of permission request occurs on iOS is through an asynchronous dialog prompt, which is only shown if needed (and not until it is needed). Basically, you need to set up a callback from the CLLocation API. I have a helper class that I use for this purpose, which makes it even easier. Just call GetCurrentDeviceLocation() and pass it a callback function. The callback will only be invoked once the user has granted permission to the app, or if they previously granted permission:
public class GeoLocationService
{
readonly CLLocationManager _locationManager;
WeakReference<Action<Position>> _callback;
public GeoLocationService()
{
_locationManager = new CLLocationManager ();
_locationManager.AuthorizationChanged += AuthorizationChanged;
}
void AuthorizationChanged (object sender, CLAuthorizationChangedEventArgs e)
{
Action<Position> callback;
if (_callback == null || !_callback.TryGetTarget (out callback)) {
return;
}
if (IsAuthorized(e.Status)) {
var loc = _locationManager.Location;
var pos = new Position(loc.Coordinate.Latitude, loc.Coordinate.Longitude);
callback (pos);
}
}
static bool IsAuthorized(CLAuthorizationStatus status)
{
return
status == CLAuthorizationStatus.Authorized
|| status == CLAuthorizationStatus.AuthorizedAlways
|| status == CLAuthorizationStatus.AuthorizedWhenInUse;
}
public void GetCurrentDeviceLocation (Action<Position> callback)
{
_callback = new WeakReference<Action<Position>> (callback);
if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
if (_locationManager.Location == null) {
_locationManager.RequestWhenInUseAuthorization ();
return;
}
}
AuthorizationChanged (null, new CLAuthorizationChangedEventArgs (CLAuthorizationStatus.Authorized));
}
}

Error in FB.login() phonegap facebook plugin

When i run fb.login() in an ios 6 device using the account setted in Settings/facebook i get the following
operation couldn't be completed (com.facebook.sdk error 2)
in ios 5 the app works perfectly, the problem is the native login
help please ! this is my code
this is the facebook init
this.appId = appId;
var me = this;
document.addEventListener('deviceready', function() {
try {
FB.init({ appId: "294003447379425", status: true, cookie: true, nativeInterface: CDV.FB, useCachedDialogs: false });
} catch (e) {
console.log(e);
}
}, false);
if (!this.appId) {
Ext.Logger.error('No Facebook Application ID set.');
return;
}
var me = this;
me.hasCheckedStatus = false;
FB.Event.subscribe('auth.logout', function() {
// This event can be fired as soon as the page loads which may cause undesired behaviour, so we wait
// until after we've specifically checked the login status.
if (me.hasCheckedStatus) {
me.fireEvent('logout');
}
});
// Get the user login status from Facebook.
FB.getLoginStatus(function(response) {
me.fireEvent('loginStatus');
clearTimeout(me.fbLoginTimeout);
me.hasCheckedStatus = true;
if (response.status == 'connected') {
me.fireEvent('connected');
Ext.Viewport.add(Ext.create('CinePass.view.Main'));
} else {
me.fireEvent('unauthorized');
console.log('noconectado');
Ext.Viewport.add(Ext.create('CinePass.view.LoggedOut'));
}
});
// We set a timeout in case there is no response from the Facebook `init` method. This often happens if the
// Facebook application is incorrectly configured (for example if the browser URL does not match the one
// configured on the Facebook app.)
me.fbLoginTimeout = setTimeout(function() {
me.fireEvent('loginStatus');
me.fireEvent('exception', {
type: 'timeout',
msg: 'The request to Facebook timed out.'
});
Ext.Msg.alert('CinePass', 'Existe un problema con Facebook, se iniciará la aplicación sin conexión a Facebook.', Ext.emptyFn);
Ext.Viewport.add(Ext.create('CinePass.view.Main'));
}, me.fbTimeout);
this is the login
FB.login(
function(response) {
if (response.session) {
alert(response.session);
} else {
alert(response.session);
}
},
{ scope: "email,user_about_me,user_activities,user_birthday,user_hometown,user_interests,user_likes,user_location,friends_interests" }
);
Having the same problem and took me few days to figure this out, there are a number of reasons:
1) The first time you launch your app, if you deny the "Do you allow this app to use your facebook permission", you'll get this error, what you need to do is, go to Setting > General > Facebook > turn on your app OR go to Setting > General > Reset > Reset Location & Privacy (this will reset and ask you the "Do you allow this app to use your facebook permission" again for all app.
2) Slow/No Internet can caused the error
3) Create your certificate again, and go to build.phonegap.com, create a new key for IOS and change the IOS key (This works for me, I have no idea how it works but it does, I notice a significant app file size increase after i use a new IOS Key)
4) If your app is in sand box mode, and your IOS current Facebook account is not an app tester you'll get the error too. I just disable the sand box mode and it works, make sure your Facebook App Setting has the correct bundle ID, if your app is still under developement, put 0 to app store ID.

message queue full error in blackberry

I have coded to get the info from the user and send an email of clicking a button. The program is getting executed for a while and then the simulator is crashing showing error
"DE427"-Message queue full... Here's the code that i have done...
if(field==SendMail)
{
Message m = new Message();
Address a = null;
try {
a = new Address("user#xyz.com", "Rahul");
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Address[] addresses = {a};
try {
m.addRecipients(net.rim.blackberry.api.mail.Message.RecipientType.TO, addresses);
m.setContent("Name:"+Name.getText().toString()+"\n"+ "Phone :"+Phone.getText().toString()+
"\n"+ "Date & Time:"+DateShow.getText().toString()+"\n"+"Make:"+Make.getText().toString()+
"\n"+"Model:"+Model.getText().toString()+"\n"+"Miles:"+Miles.getText().toString()+"\n");
m.setSubject("Appointment Request (Via Blackberry app)");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(m));
}
Can anyone tell me what the error is and how to rectify the problem....Plz...
It seems there is an issue with certain versions of Windows XP and the Blackberry simulator version. Check this link http://supportforums.blackberry.com/t5/Testing-and-Deployment/Simulator-quot-device-Error-DE427-quot/m-p/556321
If you clean up the simulator (delete .dmp files from simulator directory) and restart the simulator it works fine

Resources