Xam.Plugin.Media Get Path - xamarin

I am using Xam.Media.Plugin to take pictures. The following is a snippet of my function:
public async Task<string> TakePhoto(string orderNr)
{
...
var mediaOptions = new StoreCameraMediaOptions()
{
CompressionQuality = 25,
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Custom,
CustomPhotoSize = 75,
Directory = $"Order_{orderNr}"
};
var file = await CrossMedia.Current.TakePhotoAsync(mediaOptions);
}
After the order is completed, I want to delete the entire folder with all of the pictures that were saved. How do I retrieve the path of the folder? I want to avoid getting the path after the picture is taken.

on Android,
Environment.DirectoryPictures
on iOS
Environment.SpecialFolder.Personal
from Github

To get the private path var privatePath = file.Path;
To get the public Album path var publicAlbumPath = file.AlbumPath;
Reference: Documentation sample project

Related

receive file in my xamarin app from another's app share function

How to receive file in my xamarin app from another's app share function?
if (Intent.Action == Intent.ActionSend)
{
{
// This is just an example of the data stored in the extras
var uriFromExtras = Intent.GetParcelableExtra(Intent.ExtraStream) asAndroid.Net.Uri;
var subject = Intent.GetStringExtra(Intent.ExtraSubject);
// Get the info from ClipData
var pdf = Intent.ClipData.GetItemAt(0);
// Open a stream from the URI
var pdfStream = ContentResolver.OpenInputStream(pdf.Uri);
// Save it over
var memOfPdf = new System.IO.MemoryStream();
pdfStream.CopyTo(memOfPdf);
var docsPath = System.Environment.GetFolderPat(System.Environment.SpecialFolder.Personal);
var filePath = System.IO.Path.Combine(docsPath, "temp.pdf");
System.IO.File.WriteAllBytes(filePath, memOfPdf.ToArray());
mainForms.DisplayThePDF(filePath);
}
}
this is only for PDF and also not working well.

How to load network image in Flame?

In Flame documentation, Image class just load from asset folder.
bgSprite = Sprite('avatar/avatar-sample.png');
How can I load network images in Flame.
You could do something like this in versions after 1.0.0:
import dart:ui; // This is the package you want the Image class from, there are several
Future<Image> getImage(String path) async {
Completer<ImageInfo> completer = Completer();
var img = new NetworkImage(path);
img.resolve(ImageConfiguration()).addListener(ImageStreamListener((ImageInfo info,bool _){
completer.complete(info);
}));
ImageInfo imageInfo = await completer.future;
return imageInfo.image;
}
and then in your onLoad method, just initiate bgSprite:
#override
Future<void> onLoad() async {
final image = await getImage("your-url.com/sample.png");
bgSprite = Sprite(image);
}
In 0.28.0, which it looks like you are running, you'll just replace the last line with (but I really recommend upgrading to a version after 1.0.0):
bgSprite = Sprite.fromImage(image);

Xamarin display notification in notification bar once the file is downloaded

I have this code for downloading a file which runs correct:
var base64EncodedBytes = System.Convert.FromBase64String(item.FileDataAsBase64String);
var downloadDirectory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
var filePath = Path.Combine(downloadDirectory, "test.pdf");
var streamWriter = File.Create(filePath);
streamWriter.Close();
File.WriteAllBytes(filePath, base64EncodedBytes);
I'm able to locate the file I downloaded in the Downloads folder, but also I want to show a notification in the notification bar that the file has been downloaded and with a click in the notifications the user to be able to open the downloaded file.
Is that possible?
You can use Plugin.LocalNotification to show the notification once the file is downloaded.
try
{
var base64EncodedBytes = System.Convert.FromBase64String(item.FileDataAsBase64String);
var downloadDirectory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
var filePath = Path.Combine(downloadDirectory, "test.pdf");
var streamWriter = File.Create(filePath);
streamWriter.Close();
File.WriteAllBytes(filePath, base64EncodedBytes);
DisplayNotification("test.pdf downloaded successfully", filePath);
}
catch(System.Exception e)
{
System.Console.WriteLine(e.ToString());
DisplayNotification("Download Failed",string.Empty);
}
public void DisplayNotification(string message, string filePath)
{
var notification = new NotificationRequest
{
NotificationId = 100,
Title = "Your App name",
Description = message,
ReturningData = filePath, // Returning data when tapped on notification.
NotifyTime = DateTime.Now.AddSeconds(30) // Used for Scheduling local notification, if not specified notification will show immediately.
};
NotificationCenter.Current.Show(notification);
}
Note: Make sure to initialize the plugin setup in both the project iOS and Android.

how to save a drawingpad image in nativescript

UPDATE
now its working, see the answer below (https://stackoverflow.com/a/43983621/2844901)
this is my getDrawing function, I need to save the signature from drawing to a file in file system, I've tried everything and I cant get the saveToFile demo in nativescript docs to get it work.
exports.getDrawing = function(args) {
var pad = frameModule.topmost().currentPage.getViewById("drawingPad");
// then access the 'drawing' property (Bitmap on Android) of the signaturepad
var img = frameModule.topmost().currentPage.getViewById("imagesignature");
pad.getDrawing().then(function(result){
img.src = result; // <-- this shows in an image label the drawing signature
########### this part should be save the file,but I don't get any error, and it doesn't save it to a file, when tried to dump "img" ############
var img2 = imageSource.fromAsset(result);
var folder = fs.knownFolders.documents();
var path = fs.path.join(folder.path, "Test.png");
var saved = img2.saveToFile(path, "png");
});
}
the problem was, the getDrawing() does not return a promise it returns an image so the correct code should be a NativeSource.
pad.getDrawing().then(function(result){
img.src = result;
console.log("1");
var img2 = imageSource.fromNativeSource(result);
var folder = fs.knownFolders.documents();
var path = fs.path.join(folder.path, "Test.png");
var saved = img2.saveToFile(path, "png");
console.log("saved: " + saved);
console.log("IMAGEN SRC.....");
});

Dynamically display image in IOS xamarin - nitWithContentsOfFile:' method returned nil

I have a portable xamarin application with some "specific overrides" for android and ios.
I have a content page with image that need to be downloaded from server.
Since the image is not "public" on the server I cannot use a simple url to add the image to the Image control.
So my code is downloading the image, save it locally and then pass the image url to the Image control:
string filePath = GetThumbnailPath();
Image img = new Image
{
HorizontalOptions = LayoutOptions.CenterAndExpand,
WidthRequest = 150,
HeightRequest = 150,
Source = FileImageSource.FromFile(filePath),
Margin = new Thickness(0, 10, 0, 10)
};
layout.Children.Add(img);
On android everything works great.
On IOS the image is saved to:
string directory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filePath = Path.Combine(directory, "thumbnail.jpg");
but when the page is loaded the application crash with:
System.Exception: Could not initialize an instance of the type 'UIKit.UIImage': the native 'initWithContentsOfFile:' method returned nil.
I cannot change the image to be a bundled resource (its dynamic) and cannot make the server call public (its an handler require header parameters or cookies)
On iOS you can save image to local storage with this code:
var rootFolder = FileSystem.Current.LocalStorage;
var folder = await rootFolder.CreateFolderAsync("Images", CreationCollisionOption.OpenIfExists);
var file = await folder.CreateFileAsync("image.png", CreationCollisionOption.ReplaceExisting);
var httpClient = new HttpClient();
var buffer = await httpClient.GetByteArrayAsync(url);
using (Stream stream = await file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite))
{
stream.Write(buffer, 0, buffer.Length);
}
return file.Path;
Than, you can show that image with:
var imageSource = new FileImageSource { File = filePath};
MyPicture.Source = imageSource;
Where MyPicture is defined with:
<Image x:Name="MyPicture">

Resources