How to open Apple Maps using Flutter/Dart? - ios

Our Flutter App shows a number of locations using Google Maps, if available, or else using the local browser.
Although we had already previously uploaded a binary code for iOS which was accepted by Apple and successfully published in the App Store, now that we have added some more locations and thus attempted to publish a new version, Apple has rejected our binary, stating that it is mandatory to use "Apple Maps" instead of anything that starts with a "G", like Google...
The rejection message reads as follows:
Your app's location feature is not integrated with the built-in mapping functionality, which limits users to a third-party maps app.
Next Steps
To resolve this issue, please revise your app to give users the option to launch the native Apple Maps app.
I have found that there exists some documentation about a Javascript library named MapKit JS, which serves precisely the purpose of interacting with Apple Maps: https://developer.apple.com/maps/mapkitjs/
<script src="https://cdn.apple-mapkit.com/mk/5.x.x/mapkit.js"></script>
<script>
mapkit.init({
authorizationCallback: function(done) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/services/jwt");
xhr.addEventListener("load", function() {
done(this.responseText);
});
xhr.send();
}
});
var Cupertino = new mapkit.CoordinateRegion(
new mapkit.Coordinate(37.3316850890998, -122.030067374026),
new mapkit.CoordinateSpan(0.167647972, 0.354985255)
);
var map = new mapkit.Map("map");
map.region = Cupertino;
</script>
Nevertheless, I could really use some help no how to connect with this MapKit JS using DART, instead of JAVA, for our Flutter application.
Thank you immensely for your kind help!
Daniel

Firstly, install the url_launcher plugin
Secondly, add the below code in Info.plist:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>googlechromes</string>
<string>comgooglemaps</string>
</array>
Thirdly:
var urlAppleMaps = 'https://maps.apple.com/?q=$lat,$lng';
if (await canLaunch(urlAppleMaps)) {
await launch(urlAppleMaps);
} else {
throw 'Could not launch $url';
}
We can use it like this:
_launchMap(BuildContext context, lat, lng) async {
var url = '';
var urlAppleMaps = '';
if (Platform.isAndroid) {
url = "https://www.google.com/maps/search/?api=1&query=${lat},${lng}";
} else {
urlAppleMaps = 'https://maps.apple.com/?q=$lat,$lng';
url = "comgooglemaps://?saddr=&daddr=$lat,$lng&directionsmode=driving";
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
if (await canLaunch(url)) {
await launch(url);
} else if (await canLaunch(urlAppleMaps)) {
await launch(urlAppleMaps);
} else {
throw 'Could not launch $url';
}
}

You could try to use a Map Launcher plugin to launch apple/google maps depending on a platform
import 'dart:io';
import 'package:map_launcher/map_launcher.dart';
if (Platform.isIOS) {
await MapLauncher.launchMap(
mapType: MapType.apple,
coords: Coords(31.233568, 121.505504),
title: "Shanghai Tower",
description: "Asia's tallest building",
);
} else {
await MapLauncher.launchMap(
mapType: MapType.google,
coords: Coords(31.233568, 121.505504),
title: "Shanghai Tower",
description: "Asia's tallest building",
);
}

Just an idea but maybe you can try to use the url_launch plugin to launch a url following the schemata given in the apple maps url schemata given here: https://developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html#//apple_ref/doc/uid/TP40007899-CH5-SW1

A simple solution I have found is to replace the google maps URL with a maps.apple.com equivalent, using the same url_launcher function.
For example, the original function for Google Maps:
void _mapaBethania() async {
const url = "https://www.google.com/maps/place/Panamanian+Institute+for+Special+Training/#9.0067418,-79.5300556,17z/data=!3m1!4b1!4m5!3m4!1s0x8faca84549395297:0x9c54b1fdb96ac590!8m2!3d9.0067365!4d-79.5278669";
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Lo sentimos, no es posible abrir: $url';
}
}
Has become:
void _mapaBethania() async {
const url = "https://maps.apple.com/?q=IPHE&ll=9.0067418,-79.5300556&z=16";
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Lo sentimos, no es posible abrir: $url';
}
}
Nevertheless, although this change does fulfill Apple's enforced obligation to use their own software instead of the competition's, the user experience with Apple Maps is very poor, because once the Map App is shown, it becomes a bit confusing and difficult to return back to the original App.
Therefore, I am planning to write code that enables both options, Apple Maps in order to comply with Apple enforcement, and also Google Maps in order to provide a better user experience, despite Apple.
Anyway, the latter is just a personal opinion; the true fact is that replacing the URL for a maps.apple.com equivalent using the same launch_url function, does seem acceptable to comply with Apple requirements.

Related

Supabase Auth - redirectTo not working for OAuth

I am switching from Flutter to Supabase and am running into an issue with Authentication. Although I can successfully launch the URL with the correct redirect value, I keep getting redirected to the site URL which should only be used for web, not iOS or Android. Below is the function I am using for Apple but this is happening with all other providers as well.
const isWeb = Platform.OS === "web";
const redirectTo = isWeb
? "https://web.example.com/login-callback/"
: "com.example.react://login-callback/";
export const signInWithApple = async () => {
const { data, error } = await supabase.auth.signInWithOAuth({
provider: "apple",
options: {
redirectTo: redirectTo,
},
});
if (error !== null) {
console.log(error?.message);
return "error";
} else {
console.log(data);
Linking.openURL(data.url);
return "success";
}
};
The URL that gets logged before launching is correct, for example, LOG {"provider": "apple", "url": "https://api.example.com/auth/v1/authorize?provider=apple&redirect_to=com.example.react%3A%2F%2Flogin-callback%2F"}, but I always get redirected to something like https://web.example.com/#access_token=*****. I had a similar issue with Flutter, and that was because I had not added the additional redirect in Supabase but I already did that. I also confirmed that I have CFBundleURLSchemes set in the info.plist for iOS but that did not fix it.
IF SELF-HOSTING:
Check that you do not have spaces after commas in ADDITIONAL_REDIRECT_URLS.
Correct ✅ :
ADDITIONAL_REDIRECT_URLS="URL,URL,URL"
Incorrect ❌ :
ADDITIONAL_REDIRECT_URLS="URL, URL, URL"

The dialer is not showing full ussd code eg: *123*1#

I am using the url_launcher plugin for call, but the dialer is not showing the # character:
String url = 'tel:*123#';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
You need to use URL encoding for special character in a URL.
So # equals %23
This will work launch('tel:\*123\%23');
Other Way is to encode the number typed by user and pass it through Uri.encodeFull(urlString) or Uri.encodeComponent(urlString)
Like this.
launch("tel:" + Uri.encodeComponent('*123#'));
Disclaimer: plugin author here.
Do you want the phone call user interface to open or would you rather make the request silently? If you prefer to do it without popping the phone call UI, Android introduced in API level 26 the method sendUssdRequest.
I made a Flutter plugin called ussd_service to be able to easily access it from dart in a Flutter application. It can be used in the following manner:
import 'package:ussd_service/ussd_service.dart';
makeMyRequest() async {
int subscriptionId = 1; // sim card subscription Id
String code = "*21#"; // ussd code payload
try {
String ussdSuccessMessage = await UssdService.makeRequest(subscriptionId, code);
print("succes! message: $ussdSuccessMessage");
} on PlatformException catch (e) {
print("error! code: ${e.code} - message: ${e.message}");
}
};
makeMyRequest();
Hope this helps! Let me know on the Github repo's issues if you have any issue with it.

ViberApp is existing in IONIC IOS

Now I'm developing IOS App and I want to check if the Viber App is existing in the Phone or not.
I already use Viber:\\ URL scheme and https://ionicframework.com/docs/native/app-availability/ to check the app but the app is not detecting
There's any possible implementation?
Thanks
Try this;
import { AppAvailability } from '#ionic-native/app-availability';
import { Platform } from 'ionic-angular';
constructor(private appAvailability: AppAvailability, private platform: Platform) { }
let app;
if (this.platform.is('ios')) {
app = 'Viber://';
} else if (this.platform.is('android')) {
app = 'com.viber.voip ';
}
this.appAvailability.check(app)
.then(
(yes: boolean) => console.log(app + ' is available'),
(no: boolean) => console.log(app + ' is NOT available')
);
the URLScheme must be declared publicly in Info.plist file first
visit this UseYourLoaf tutorial for more details
i fixed it by check if these is exist
viber = "https://itunes.apple.com/ph/app/viber-messenger-chats-calls/id382617920?mt=8"
and
use app-availability
this.appAvailability.check(viber)

Flutter: Location package Not working on First Time App Install

My current app uses the Location package (link) to obtain the user's current latitude and longitude to be used to find nearby facilities.
This is the code I am using (similar to the example in the documentation)
Map<String, double> _currentLocation;
Map<String, double> _startLocation;
StreamSubscription<Map<String, double>> _locationSubscription;
String error;
bool _permission = false;
Location _location = new Location();
// Platform messages are asynchronous, so we initialize in an async method.
initPlatformState() async {
Map<String, double> location;
try {
_permission = await _location.hasPermission();
location = await _location.getLocation();
error = null;
} on PlatformException catch (e) {
if (e.code == 'PERMISSION_DENIED') {
error = 'Permission denied';
} else if (e.code == 'PERMISSION_DENIED_NEVER_ASK') {
error = 'Permission denied - please ask the user to enable it from the app settings';
}
location = null;
}
setState(() {
_startLocation = location;
print("Starting coordinates: ${_startLocation["latitude"]}, ${_startLocation["longitude"]}");
});
}
#override
void initState() {
super.initState();
initPlatformState();
_locationSubscription =
_location.onLocationChanged().listen((Map<String,double> result) {
setState(() {
_currentLocation = result;
print("Current coordinates: ${_currentLocation["latitude"]}, ${_currentLocation["longitude"]}");
});
});
}
The only problem I am facing is that whenever there is a fresh install of a new apk of the app, the app does not find the location after location permission has been granted.
After location has been granted I have set up a print statement to print out the user's location but for some reason it is not printing anything the first time only. After I restart the app then it prints out the location just fine.
First Time Opening After Install
After Restarting the App
Any experts that use the Location package that could help me with this problem?
According to plugin’s source code when you invoke getLocation method it asks ActivityCompat.requestPermissions to get required permission and then process. According to docs from Google:
This method functions asynchronously. It returns right away, and after the user responds to the prompt, the system calls the app's callback method with the results
, but flutter plugin has an issue about location callbacks for Android 6+ and as a workaround it is recommended to aim SDK 21.
So it seems that “native” part of this plugin doesn’t play well with Android 6+. There are two workarounds:
Set SDK to 21 version for your Android project, but I would definitely not recommend doing that.
Create some sort of “hello screen”, which will introduce the app and handle permissions there.
Meanwhile, I am really interested in what is wrong with the plugin cause its implementation seems good, so in case I’ll find how to fix it I’ll get back here.

Phonegap - Share functionality to Email, Twitter and Facebook

Is there an example how to program the functionality with the Phonegap Framework to share a URL to email, twitter and Facebook? For Example in Android this functionality is in 90% of the apps. In Iphone it is in any Apps. In the app of techcrunch for Iphone you can see it, when You open an article. Is it possible to create this with Phonegap too?
You can do this in Android with the following code for a plugin. I haven't published this anywhere else yet, but eventually I hope to add it as a plugin in the phonegap plugin repository for Android.
JAVASCRIPT:
var Share = function() {};
Share.prototype.show = function(content) {
return PhoneGap.exec(
function(args) {
console.log("phonegap share plugin - success!")
}, function(args) {
console.log("phonegap share plugin - failed")
}, 'Share', '', content);
};
PhoneGap.addConstructor(function() {
PhoneGap.addPlugin('share', new Share());
PluginManager.addService("Share","com.COMPANYNAME(CHANGEME).android.plugins.Share");
});
JAVA IN ANDROID:
package com.COMPANYNAME(CHANGEME).android.plugins;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Intent;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
public class Share extends Plugin {
private String callback;
#Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult mPlugin = null;
try {
mPlugin = activateSharing(args.getString(0), args.getString(1));
} catch (JSONException e) {
Log.e("JSON Exception", e.toString());
}
mPlugin.setKeepCallback(true);
this.callback = callbackId;
return mPlugin;
}
private PluginResult activateSharing(String title, String body) {
final Intent shareIntent = new Intent(
android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, title);
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(Intent.createChooser(shareIntent, "Share"));
return new PluginResult(PluginResult.Status.OK);
}
}
Almost three years later: Here's a plugin that allows sharing on Android and iOS with the same API. https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin
It's available on PhoneGap Build as well!
Example
window.plugins.socialsharing.share('Google is awesome, WOOT!', 'Google facts', 'https://www.google.com/images/srpr/logo11w.png', 'http://www.google.com');
Login Facebook and post feed, login twitter and post status using plugin appInBrowser:
https://github.com/raulduran/facebook-twitter-cordova.git

Resources