Reputation: 1560
I'm working with a .NET iOS (formerly Xamarin.iOS) app and I want to access an image shared from the Files or Photos app. I’ve tried implementing a Share Extension without a UI, but it’s not working as expected. Additionally, the debugger is not functioning properly in the .NET iOS extension project.
Is there a correct way to achieve this in .NET iOS, either with or without a share extension?
What I have tried already :
void LoadImage (NSExtensionContext extensionContext = null) {
var image = new NSExtensionItem [0];
NSExtensionItem inputItem;
if (extensionContext == null) {
inputItem = ExtensionContext.InputItems [0];
}
else {
inputItem = extensionContext.InputItems [0];
}
var outputItem = inputItem.Copy () as NSExtensionItem;
var itemProvider = outputItem.Attachments [0];
string imageTypeIdentifier = "public.image";
string pdfTypeIdentifier = "com.adobe.pdf";
var test = itemProvider.GetRegisteredTypeIdentifiers (NSItemProviderFileOptions.OpenInPlace);
if (!(itemProvider.HasItemConformingTo (imageTypeIdentifier)) || itemProvider.HasItemConformingTo (pdfTypeIdentifier)) {
OpenUrl (NSUrl.FromString ($"myapp://itemtypeimagedoesnotexists)"));
return;
}
itemProvider.LoadItem (imageTypeIdentifier, null, (item, loadError) => {
if (item != null && loadError == null) {
InvokeOnMainThread (() => {
OpenUrl (NSUrl.FromString ($"myapp://{item.ToString ()}"));
if (item is UIImage) {
SaveImageToAppGroup (item as UIImage, "shared_image_url.txt");
}
});
}
else {
InvokeOnMainThread (() => {
OpenUrl (NSUrl.FromString ($"myapp://itemisnullorhasloaderror"));
});
}
});
itemProvider.LoadItem (pdfTypeIdentifier, null, (item, loadError) => {
if (item != null && loadError == null) {
InvokeOnMainThread (() => {
OpenUrl (NSUrl.FromString ($"myapp://{item.ToString ()}"));
if (item is NSData) {
SavePdfToAppGroup (item as NSData, "shared_image_pdf.txt");
}
});
}
else {
InvokeOnMainThread (() => {
OpenUrl (NSUrl.FromString ($"myapp://itemisnullorhasloaderror"));
});
}
});
}
public void SaveImageToAppGroup (UIImage image, string fileName) {
var appGroupPath = NSFileManager.DefaultManager.GetContainerUrl (APP_GROUP_IDENTIFIER);
var directoryPath = appGroupPath.Path;
if (!NSFileManager.DefaultManager.FileExists (directoryPath)) {
NSError createDirError = null;
NSFileManager.DefaultManager.CreateDirectory (appGroupPath, true, null, out createDirError);
}
NSData imgData = image.AsJPEG ();
var filePath = Path.Combine (directoryPath, fileName);
NSError saveError = null;
imgData.Save (filePath, NSDataWritingOptions.Atomic, out saveError);
}
Here, file is not saved in app group using extension. So, I can not read it in the app as well.
Any leads ?
Upvotes: 0
Views: 68