Connectivity plugin "getWifiName()" method to get ssid returns null in flutter for ios 13+ - flutter

I am trying to get wifi ssid in flutter for ios(13+) with connectivity plugin but result returns null. I have added access wireless information from Xcode but still not working. Can anyone help out please?
Future<void> _updateConnectionStatus(ConnectivityResult result) async{
switch(result){
case ConnectivityResult.wifi:
String wifiName;
try {
if (Platform.isIOS) {
LocationAuthorizationStatus status =
await _connectivity.getLocationServiceAuthorization();
if (status == LocationAuthorizationStatus.notDetermined) {
print('wifiName notDetermined: ');
status = await _connectivity.requestLocationServiceAuthorization();
}
if (status == LocationAuthorizationStatus.authorizedAlways ||
status == LocationAuthorizationStatus.authorizedWhenInUse) {
print('wifiName authorizedWhenInUse: ');
wifiName = await _connectivity.getWifiName();
setState(() {
_ssid = wifiName != null ? wifiName : _ssid;
});
} else {
print('wifiName ,.,.,.,: ');
wifiName = await _connectivity.getWifiName();
}
} else {
LocationAuthorizationStatus status =
await _connectivity.getLocationServiceAuthorization();
// if(status == )
wifiName = await _connectivity.getWifiName();
print('android wifi');
print(wifiName);
}
} on PlatformException catch (e) {
print(e.toString());
wifiName = "Failed to get Wifi Name";
}
setState(() {
_connectionStatus ='result '+ '$result\n'
'Wifi Name: $wifiName\n';
print('_connectionStatus $_connectionStatus');
});
break;
case ConnectivityResult.mobile:
Fluttertoast.showToast(msg: 'Connected to mobile network');
break;
case ConnectivityResult.none:
Fluttertoast.showToast(msg: 'Connected to no network');
setState(() => _connectionStatus = result.toString());
break;
default:
setState(() => _connectionStatus = 'Failed to get connectivity.');
break;
}
}
I have tried with above code from connectivity plugin example. Also there is showing 'As of iOS 13, Apple announced that these APIs will no longer return valid information'. So how to achieve my goal?

In 2020, the flutter team decided to create a new plugin for wifi information, removing these methods from the connectivity plugin.
So check the network_info_plus plugin: the method signatures are just the same.
As on being able to access this on iOS 13+, according to the package's readme:
The CNCopyCurrentNetworkInfo will work for Apps that:
The app uses Core Location, and has the user’s authorization to use
location information.
The app uses the NEHotspotConfiguration API to configure the current
Wi-Fi network.
The app has active VPN configurations installed.
If your app falls into the last two categories, it will work as it is.
If your app doesn't fall into the last two categories, and you still
need to access the wifi information, you should request user's
authorization to use location information.
There is a helper method provided in this plugin to request the
location authorization: requestLocationServiceAuthorization. To
request location authorization, make sure to add the following keys to
your Info.plist file, located in /ios/Runner/Info.plist:
NSLocationAlwaysAndWhenInUseUsageDescription - describe why the app
needs access to the user’s location information all the time
(foreground and background). This is called Privacy - Location Always
and When In Use Usage Description in the visual editor.
NSLocationWhenInUseUsageDescription - describe why the app needs
access to the user’s location information when the app is running in
the foreground. This is called Privacy - Location When In Use Usage
Description in the visual editor.
So basically, from iOS13 on, you have to request the user's permission for location - it actually makes sense.

Related

Permissions always returns "Granted" for Permissions.Photos in .net MAUI

I am using below code to access gallery permissions in .net maui but it always returns Granted even on first time launch of the application and I am not able to see the permission popup saying "This app would like to access photos and media on your device"
public static async Task<PermissionStatus> GetMediaPermissionStatus()
{
PermissionStatus mediaResult = PermissionStatus.Disabled;
var tcs = new TaskCompletionSource<PermissionStatus>();
var status = await Permissions.CheckStatusAsync<Permissions.Photos>();
if (status != PermissionStatus.Granted)
{
status = await Permissions.RequestAsync<Permissions.Photos>();
}
tcs.SetResult(status);
return await tcs.Task;
}
Also when I execute below code getting 2 app permission Popups
1st Popup - "Allow application to take pictures and record video"
2nd Popup - "Allow application to access photos and media on your device?"
public async void TakePhoto()
{
if (MediaPicker.Default.IsCaptureSupported)
{
FileResult photo = await Microsoft.Maui.Media.MediaPicker.Default.CapturePhotoAsync();
if (photo != null)
{
// save the file into local storage
string localFilePath = Path.Combine(FileSystem.CacheDirectory, photo.FileName);
using Stream sourceStream = await photo.OpenReadAsync();
using FileStream localFileStream = File.OpenWrite(localFilePath);
await sourceStream.CopyToAsync(localFileStream);
}
}
}
I don't know if it is a bug or I am doing something wrong.
Any help is appreciated!
You can refer to this doc: Permissions of MAUI. There is a table in it. It uses ✔️ to indicate that the permission is supported and ❌ to indicate the permission isn't supported or isn't required
If a permission is marked as ❌, it will always return Granted when checked or requested.
Granted:
The user granted permission or is automatically granted.
Wish it can help you.

Flutter permission_handler : request location permission on iOS

I want to ask user to enable permission only if he denied the permission or the permission is not allowed
This function is working very well on android
Future _getLocationPermission() async {
if (await Permission.location.request().isGranted) {
permissionGranted = true;
} else if (await Permission.location.request().isPermanentlyDenied) {
throw('location.request().isPermanentlyDenied');
} else if (await Permission.location.request().isDenied) {
throw('location.request().isDenied');
permissionGranted = false;
}
}
but on iOS it throw exception permission isPermanentlyDenied
Unhandled Exception: location.request().isPermanentlyDenied
even if the user allowed location permission while using app
I'm using permission_handler package
iOS is stricter, it does not allow you to request for permission if the user has already permanently denied it. In this case your only option is to inform the user about this, and offer the possibility to open application settings and grant permission there. This will likely restart your application if the user grants.
So check the status without requesting:
final status = await Permission.location.status;
If status is permanently denied, display a Flutter dialog (you can't use the system permission grant dialog in this case):
if (status == PermissionStatus.permanentlyDenied) {
// display a dialog, explain the user that he/she can grant
// permission only in the phone's application settings
}
If the user want's to do it, you can route to the application settings:
openAppSettings(); // this is a method of the permission handler package
This method is a future, but in my experience you don't need to await it.
This is just a function that returns bool if the user enables location
or not simple
Future<bool> canGetLocation(Location location) async {
if (!await location.requestService()) return false;
final status = await location.requestPermission();
final granted = PermissionStatus.granted;
final grantedLimited = PermissionStatus.grantedLimited;
bool result = status == granted || status == granted;
return result;
}
if (await canGetLocation(location)) {
// Do something
} else {
final status = await handler.Permission.location.status;
if (status.isPermanentlyDenied || status.isDenied) {
// ask the user to open the app setting
// from permission handler package you have
openAppSettings();
} else {
// show info dialog or something that the user need to enable location services
}
}
Please check this link. You must have to mention permission in POD file also.

can't load iap products in local, it waits forever

I'm using the official in_app_purchase plugin, version ^1.0.4, and I'm following the official guide from Google insert my first iap (https://codelabs.developers.google.com/codelabs/flutter-in-app-purchases#0).
My consumable iap product is active on Play console with name "pacchetto_25", I've already submitted to the alpha channel my app and is accepted, the tester email is correctly configured in the Tester Group and in Licence Testing.
Now I'm trying to load the iap products in my app, the code is the same of the guide:
Future<void> loadPurchases() async {
final available = await _iap.isAvailable();
if (!available) {
print("STORE NOT AVAILABLE");
return;
} else {
print("STORE AVAILABLE");
const ids = <String>{
"pacchetto_25",
};
final response = await _iap.queryProductDetails(ids);
response.notFoundIDs.forEach((element) {
print('Purchase $element not found');
});
response.productDetails.forEach((element) {
print("Purchase $element found");
});
// products =
// response.productDetails.map((e) => PurchasableProduct(e)).toList();
}
}
In my console I have the "STORE AVAILABLE" message, but then nothing else. If I put same debug point it does not stops on them, this problem appear after this line:
final response = await _iap.queryProductDetails(ids);
Do someone know what's happening? I've no errors in my console and the code after loadPurchases() is not executed, it's like is waiting forever... Any ideas?
Solved! If you have the same issue DON'T put
implementation("com.android.billingclient:billing:4.0.0")
in your build.gradle

Flutter IOS beacon not able to scan with Region and UUID settings

I have this problem is that in flutter I notice there is not able to operate or use the traditional bluetooth as there is no any library supporting it. I have tested flutter_blue-master etc. So then I saw that it can behave as beacon. So I have used the codes below. For android I just set
Region(
identifier: 'com.example.myDeviceRegion',)); its able to work. So the same I set in IOS its not able to work? So what is best workaround for blueetooth in flutter? I am using this package flutter_beacon. For the beacon broadcasting I am using this package beacon_broadcast.
initScanBeacon() async {
await flutterBeacon.initializeScanning;
await checkAllRequirements();
if (!authorizationStatusOk ||
!locationServiceEnabled ||
!bluetoothEnabled) {
print('RETURNED, authorizationStatusOk=$authorizationStatusOk, '
'locationServiceEnabled=$locationServiceEnabled, '
'bluetoothEnabled=$bluetoothEnabled');
return;
}
/*final regions = <Region>[
Region(
identifier: 'com.example.myDeviceRegion',
),
];*/
final regions = <Region>[];
regions.add(Region(
identifier: 'com.example.myDeviceRegion',
minor: 100,
major: 1));
if (_streamRanging != null) {
if (_streamRanging.isPaused) {
_streamRanging.resume();
return;
}
}
_streamRanging =
flutterBeacon.monitoring(regions).listen((MonitoringResult result) {
print(result);
if (result != null && mounted) {
print("GOT RESTULT READY");
setState(() {
//_regionBeacons[result.region] = result.region;
_beacons.clear();
print("List value is json"+result.toJson.toString());
_regionBeacons.values.forEach((list) {
print("List value is");
_beacons.addAll(list);
print("after Beacon size now is "+_beacons.length.toString());
});
//_beacons.sort(_compareParameters);
print("Beacon size now is "+_beacons.length.toString());
});
}
});
}
A few things to check:
Make sure your Region definition has a proximityUUID value. I am surprised that it works even on Android without this. On iOS it certainly won't work at all -- iOS requires a beacon proximityUUID be specified up front in order to detect. The value you give for the prximityUUID must exactly match what your beacon is advertising or you won't see it.
Make sure you have gone through all the iOS setup steps here: https://pub.dev/packages/flutter_beacon
Be extra sure that you have granted location permission to your iOS app. You can go to Settings -> Your App Name to check if location permission is granted.
Make sure bluetooth is enabled in settings for the phone
Make sure location is enabled in settings for the phone
https://pub.dev/packages/flutter_beacon
There's an update on GitHub but was yet to push to pub.dev previously.
Do update to 0.5.0.
Always check pub.dev for updates. or github reported issues.

Flutter getting an exception when calling queryPastPurchases (in_app_purchase plugin): Cannot find receipt for the current main bundle

I'm trying to utilise the in_app_purchase plugin (https://pub.dev/packages/in_app_purchase) for my Flutter App.
Calling a queryProductDetails(ids) works just fine,
but when calling the queryPastPurchases() I get the following exception:
PlatformException (PlatformException(storekit_no_receipt, Cannot find receipt for the current main bundle., null))
Seems like this is the source for the exception:
https://github.com/flutter/plugins/blob/master/packages/in_app_purchase/ios/Classes/FIAPReceiptManager.m
Worth mentioning:
I've setup an IAP in App-Store-Connect.
This IAP hasn't been sent for Apple approval yet.
App is in development, tested using TestFlight with beta testers.
Another issue is that this exception doesn't get cought in the try-catch statement (see code below), but only by the environment when checking the "All Exceptions" option in VSCode...
Tested on Emulator and real device.
[UPDATE]:
Added a breakpoint to the objective-c code of the plugin, and saw that the receiptURL refers to "sandboxReceipt". So maybe it's because I don't use sandbox users?
Future<void> _getPastPurchases() async {
try {
final QueryPurchaseDetailsResponse response = await InAppPurchaseConnection.instance.queryPastPurchases();
if (response.error != null) {
// Handle the error
print(response.error.toString());
}
print('response = ' + response.toString());
for (PurchaseDetails purchase in response.pastPurchases) {
if (Platform.isIOS) {
//InAppPurchaseConnection.instance.completePurchase(purchase);
}
}
setState(() {
_purchases = response.pastPurchases;
});
} on PlatformException catch(err) {
print(err.toString());
}
catch (err) {
print(err.toString());
}
}