Using Google Play Services location functionality with Xamarin - xamarin.android

I followed the steps mention under section "Location Client" on https://developer.xamarin.com/guides/android/platform_features/maps_and_location/location/
There in the example it implements IGooglePlayServicesClientConnectionCallbacks, IGooglePlayServicesClientOnConnectionFailedListenerinterfaces in the activity class.
From where this interface coming from? i can't resolve them in my code. What nuget package should I add and what should I import ?

From where this interface coming from? i can't resolve them in my code. What nuget package should I add and what should I import ?
You need download the Xamarin.GooglePlayServices.Base package :
And you need Check for Google Play Services when you use these api :
public bool IsPlayServicesAvailable()
{
int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.Success)
{
if (GoogleApiAvailability.Instance.IsUserResolvableError(resultCode))
msgText.Text = GoogleApiAvailability.Instance.GetErrorString(resultCode);
else
{
msgText.Text = "Sorry, this device is not supported";
Finish();
}
return false;
}
else
{
msgText.Text = "Google Play Services is available.";
return true;
}
}

Related

iOS app crashes on iphone device when using httpclient and .net maui

Build environment:
Macbook M1
vscode(1.69.0) as well as vs2022 (17.3)
Steps to reproduce:
create new Maui app
add nuget package "Microsoft.Extensions.Http" Version="6.0.0" to project
Modify MauiProgram.cs:
builder.Services.AddHttpClient<EndPointAHttpClient>(client =>
{
var EndPointA = "https://www.montemagno.com/";
client.BaseAddress = new Uri(EndPointA);
});
public class EndPointAHttpClient
{
public EndPointAHttpClient(HttpClient client)
{
Client = client;
}
public HttpClient Client { get; }
}
Publish:
dotnet publish <project.csproj> -f:net6.0-ios -c:Release /p:ServerAddress=<xxx.xxx.xxx.xxx> /p:ServerUser=user /p:TcpPort=58181 /p:ServerPassword=pwd -p:AotAssemblies=false
Install on iphone using Transporter/TestFlight
CRASHES WHEN OPENING THE APP
Please let me know:
1. Is there any demo code that works
2. Kindly provide advise on how I can use HttpClient in a .net Maui app
Use the code found here. https://github.com/dotnet/maui-samples/tree/main/6.0/WebServices/TodoREST/TodoREST/Services
Grab the RestService, IRestService, HttpsClientHandlerService and IHttpsClientHandlerService.
Get the Contstants file as well.
https://github.com/dotnet/maui-samples/blob/main/6.0/WebServices/TodoREST/TodoREST/Constants.cs
Makes sure you add your Url to the HttpsClientHandlerService like so. I was getting a System.Net.WebException: Error: TrustFailure. The only way I was able to catch what was happening was using Sentry.io. I guessed that this might be the problem.
public bool IsSafeUrl(NSUrlSessionHandler sender, string url, Security.SecTrust trust)
{
if (url.StartsWith("https://localhost") || url.StartsWith("https://yourservice.azurewebsites.net"))
return true;
return false;
}
Then change this line.
var handler = new NSUrlSessionHandler
{
TrustOverrideForUrl = IsSafeUrl
};

ionic native storage does not work on iOS

I use Ionic 3 on one of my projects with an authentication system. I use native storage when the user wants to connect. It works on Android but on iOS, it redirects me to the login screen even using platform.ready (). I saw that several people were a similar problem but no answer, so I wanted to know if someone was facing the same problem and if he found a solution. Here is my code:
this.plt.ready().then(() => {
this.nativeStorage.setItem('userStorage', { stayConnected: (typeof this.stayConnected == "undefined" || this.stayConnected == false ? '' : 'stayConnected'), userId: (result as any).id, userLogin: (result as any).login })
.then(
() => {
this.loader.dismiss();
this.navCtrl.setRoot(HomePage);
},
error => {
this.loader.dismiss();
this.presentToast(this.languageLogin.error, 3000, "bottom");
}
)
},
error => {
this.loader.dismiss();
this.presentToast(this.languageLogin.error, 3000, "bottom");
});
thank you for your answers.
I would put 2 function storeUser() and getUser() into the same provider UserService like belows
Then add UserService to the constructor of any pages required.
It works for both IOS, Android and web
import {Storage} from '#ionic/storage';
import {Observable} from 'rxjs/Observable';
#Injectable()
export class UserService {
constructor(private storage: Storage){}
public storeUser(userData): void {
this.storage.set('userData', userData);
}
public getUser(): Observable<any>
return Observable.fromPromise(this.storage.get('userData').then((val) => {
return !!val;
}));
}
Yes, I have faced issues while using ionic native storage plugins. So I turned to javascript Window localStorage Property and it's working completely fine.
Syntax for SAVING data to localStorage:
localStorage.setItem("key", "success");
Syntax for READING data from localStorage:
var lastname = localStorage.getItem("key");
Syntax for REMOVING data from localStorage:
localStorage.removeItem("key");
and now you can write your code with this property, like this -
if (lastname == "success"){
this.navCtrl.setRoot(HomePage);
} else{
alert("Not matched")
}
You are inside a platform.ready(), which is good. The storage package also has a .ready() that you may want to leverage, which specifically checks if storage itself is ready. If this runs at startup there is a decent chance storage is initializing.
Also, this starts to get into some crazy promise chaining messiness. I'd suggest diving into async/await. Something like the (untested) code below.
try{
await this.plt.ready();
await this.nativeStorage.ready();
let stayConnectedValue = (this.stayConnected) ? 'stayConnected' : '';
await this.nativeStorage.setItem('userStorage', { stayConnected: stayConnectedValue , userId: (result as any).id, userLogin: (result as any).login });
this.navCtrl.setRoot(HomePage);
}
catch(err){
this.presentToast(this.languageLogin.error, 3000, "bottom");
}
finally{
this.loader.dismiss();
}

Xamarin Notification Service Extension issue

I have an issue with Notification Service Extension.
I have followed step by step documentation
https://developer.xamarin.com/guides/ios/platform_features/introduction-to-ios10/user-notifications/enhanced-user-notifications/#Working_with_Service_Extensions
To implement, I have done in that way.
Added Notification Service Extension with same prefix of my app (adding a suffix, ex: APP: com.testapp.main - EXT: com.testapp.main.notificationextension)
Created APPID identifier com.testapp.main.notificationextension into Member Center of Apple
Created certificate and provisioning profile to send push notification for APP ID com.testapp.main.notificationextension
Imported into Xcode and Xamarin certificate and provisioning
Build my app with reference to Notification Extension reference.
Created archive to upload to TestFlight
Signed app with its Distribution Certificate and Provisioning Profile
Signed extension with its Distribution Certificate and Provisioning Profile
Uploaded to TestFlight
Download and allowed push notification for my app
Sent rich push notification with Localytics Dashboard for messaging
- Device receive push notification but not pass for NotificationService.cs code of Notification Service Extension!
This is my NotificationService code:
using System;
using Foundation;
using UserNotifications;
namespace NotificationServiceExtension
{
[Register("NotificationService")]
public class NotificationService : UNNotificationServiceExtension
{
Action<UNNotificationContent> ContentHandler { get; set; }
UNMutableNotificationContent BestAttemptContent { get; set; }
const string ATTACHMENT_IMAGE_KEY = "ll_attachment_url";
const string ATTACHMENT_TYPE_KEY = "ll_attachment_type";
const string ATTACHMENT_FILE_NAME = "-localytics-rich-push-attachment.";
protected NotificationService(IntPtr handle) : base(handle)
{
// Note: this .ctor should not contain any initialization logic.
}
public override void DidReceiveNotificationRequest(UNNotificationRequest request, Action<UNNotificationContent> contentHandler)
{
System.Diagnostics.Debug.WriteLine("Notification Service DidReceiveNotificationRequest");
ContentHandler = contentHandler;
BestAttemptContent = (UNMutableNotificationContent)request.Content.MutableCopy();
if (BestAttemptContent != null)
{
string imageURL = null;
string imageType = null;
if (BestAttemptContent.UserInfo.ContainsKey(new NSString(ATTACHMENT_IMAGE_KEY)))
{
imageURL = BestAttemptContent.UserInfo.ValueForKey(new NSString(ATTACHMENT_IMAGE_KEY)).ToString();
}
if (BestAttemptContent.UserInfo.ContainsKey(new NSString(ATTACHMENT_TYPE_KEY)))
{
imageType = BestAttemptContent.UserInfo.ValueForKey(new NSString(ATTACHMENT_TYPE_KEY)).ToString();
}
if (imageURL == null || imageType == null)
{
ContentHandler(BestAttemptContent);
return;
}
var url = NSUrl.FromString(imageURL);
var task = NSUrlSession.SharedSession.CreateDownloadTask(url, (tempFile, response, error) =>
{
if (error != null)
{
ContentHandler(BestAttemptContent);
return;
}
if (tempFile == null)
{
ContentHandler(BestAttemptContent);
return;
}
var cache = NSSearchPath.GetDirectories(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.User, true);
var cachesFolder = cache[0];
var guid = NSProcessInfo.ProcessInfo.GloballyUniqueString;
var fileName = guid + ATTACHMENT_FILE_NAME + imageType;
var cacheFile = cachesFolder + fileName;
var attachmentURL = NSUrl.CreateFileUrl(cacheFile, false, null);
NSError err = null;
NSFileManager.DefaultManager.Move(tempFile, attachmentURL, out err);
if (err != null)
{
ContentHandler(BestAttemptContent);
return;
}
UNNotificationAttachmentOptions options = null;
var attachment = UNNotificationAttachment.FromIdentifier("localytics-rich-push-attachment", attachmentURL, options, out err);
if (attachment != null)
{
BestAttemptContent.Attachments = new UNNotificationAttachment[] { attachment };
}
ContentHandler(BestAttemptContent);
return;
});
task.Resume();
}
else {
ContentHandler(BestAttemptContent);
}
}
public override void TimeWillExpire()
{
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
ContentHandler(BestAttemptContent);
return;
}
}
}
You are doing everything correctly, this is an issue raised by a few other xamarin developers. From what I can tell, as soon as you run the NSURLSession to download something, even if it's super super small, you go above the memory limit allowed for this type of extension. This is most probably very specific to xamarin.
Here is the link to the bugzilla.
https://bugzilla.xamarin.com/show_bug.cgi?id=43985
The work-around/hack I found is far from ideal. I rewrote this app extension in xcode in objective-c (you could use swift too I suppose). It is a fairly small (1 class) extension. Then built it in xcode using the same code signature certificate / provisioning profile and then found the .appex file in the xcode's output.
From then, you can take the "cheap way", and swap this .appex file in your .ipa folder manually just before resigning and submitting the app. If that's good enough for you, you can stop here.
Or you can automate this process, to to so, place the appex file in the csproj's extension and set the build-action as "content". Then in this csproj's file (you'll need to edit directly) you can add something like this. (In this case, the file is called Notifications.appex and is placed in a folder called NativeExtension)
<Target Name="BeforeCodeSign">
<ItemGroup>
<NativeExtensionDirectory Include="NativeExtension\Debug\**\*.*" />
</ItemGroup>
<!-- cleanup the application extension built with Xamarin (too heavy in memory)-->
<RemoveDir SessionId="$(BuildSessionId)"
Directories="bin\iPhone\Debug\Notifications.appex"/>
<!-- copy the native one, built in obj-c -->
<Copy
SessionId="$(BuildSessionId)"
SourceFiles="#(NativeExtensionDirectory)"
DestinationFolder="bin\iPhone\Debug\Notifications.appex"
SkipUnchangedFiles="true"
OverwriteReadOnlyFiles="true"
Retries="3"
RetryDelayMilliseconds="300"/>
</Target>
This gives you the general idea, but obviously if you want to support ad-hoc distribution signature, iOS app-store distribution signature you will need to add a bit more code into this (and possibly add in the csproj a native appex file for each different signature), I would suggest putting such xml code in separate ".targets" file and use conditional calltargets in the csproj. Like this:
<Target Name="BeforeCodeSign">
<CallTarget Targets="ImportExtension_Debug" Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhone' " />
<CallTarget Targets="ImportExtension" Condition=" '$(Configuration)|$(Platform)' == 'Release|iPhone' " />
</Target>
If anyone else comes here, the code by original poster works for me and the bug mention is now marked as fixed. If I have one tip, do not try to do this on Windows. You will be in for a whole world of pain and will get nowhere (actually, it did work for me, once!). Also expect Visual Studio on Mac to crash, a lot, if you try to debug!

Is the function 'dlopen()' private API?

I want use function 'dlopen()' to invoke a dynamic library on iOS platform, is the function 'dlopen()' private API?
I've had success using dlopen on iOS for years. In my use case, I use dlopen to load public system frameworks on demand instead of having them loaded on app launch. Works great!
[EDIT] - as of iOS 8, extensions and shared frameworks are prohibited from using dlopen, however the application itself can still use dlopen (and is now documented as being supported for not only Apple frameworks, but custom frameworks too). See the Deploying a Containing App to Older Versions of iOS section in this Apple doc: https://developer.apple.com/library/ios/documentation/General/Conceptual/ExtensibilityPG/ExtensibilityPG.pdf
[EDIT] - contrived example
#import <dlfcn.h>
void printApplicationState()
{
Class UIApplicationClass = NSClassFromString(#"UIApplication");
if (Nil == UIApplicationClass) {
void *handle = dlopen("System/Library/Frameworks/UIKit.framework/UIKit", RTLD_NOW);
if (handle) {
UIApplicationClass = NSClassFromString(#"UIApplication");
assert(UIApplicationClass != Nil);
NSInteger applicationState = [UIApplicationClass applicationState];
printf("app state: %ti\n", applicationState);
if (0 != dlclose(handle)) {
printf("dlclose failed! %s\n", dlerror());
}
} else {
printf("dlopen failed! %s\n", dlerror());
}
} else {
printf("app state: %ti\n", [UIApplicationClass applicationState]);
}
}

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