In Xamarin.Forms prerelease they have released a media picker: https://learn.microsoft.com/en-us/xamarin/essentials/media-picker?tabs=android
This is obviously a great addition and the fact that you don't have to use any 3rd party-library is great!
I'm creating an event management app - in the app the user can select an image for the event and be able to see it.
Here is my code:
public async void OnSelectPhotoCommand()
{
var photo = await MediaPicker.PickPhotoAsync();
await LoadPhotoAsync(photo);
}
async Task LoadPhotoAsync(FileResult photo)
{
var newFile = Path.Combine(FileSystem.CacheDirectory, photo.FileName);
using (var stream = await photo.OpenReadAsync())
using (var newStream = File.OpenWrite(newFile)) { await stream.CopyToAsync(newStream); }
ImagePath = newFile;
}
The problem is the image is not showing or appearing whatsoever - I've tried to modify my code and debug it but I am unable to locate the source of the problem.
I want the user to be actually able to see the image - but I am unsure on how to do that using the MediaPicker without putting it in the Android Resources folder?
Thank you,
tommy
From the xamarin essentials documentation be sure to be running it from the UI Thread.
InvokeOnMainThread ( () => {
OnSelectPhotoCommand();
});
Related
I want to record screen audio using AppRecordingManager in UWP.
I found StartRecordingToFileAsync function in AppRecordingManager Class to write audio and video content in UWP.
Here is the official document URL about this function:
https://learn.microsoft.com/en-us/uwp/api/windows.media.apprecording.apprecordingmanager.startrecordingtofileasync#Windows_Media_AppRecording_AppRecordingManager_StartRecordingToFileAsync_Windows_Storage_StorageFile_
Although I try to use this function to record audio, I always keep getting this error:
The request is invalid in the current state. (Exception from HRESULT: 0xC00D36B2)
I can not find solution for StartRecordingToFileAsync.
How can I solve this error?
Here is my c# code giving me this error.
AppRecordingManager manager = AppRecordingManager.GetDefault();
var status = manager.GetStatus();
if (status.CanRecord || status.CanRecordTimeSpan)
{
var myVideo = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Videos);
StorageFolder projectFolder = await myVideo.SaveFolder.CreateFolderAsync("DataFolder", CreationCollisionOption.OpenIfExists);
var audio = await projectFolder.CreateFileAsync("audio_record.wav", CreationCollisionOption.GenerateUniqueName);
var result = await manager.StartRecordingToFileAsync(audio);
if (result.Succeeded)
{
Debug.WriteLine(result.Succeeded);
}
else
{
Debug.WriteLine(result.ExtendedError.Message);
}
}
I managed to reproduce same error with your code.
But when I changed "audio_record.wav" to "audio_record.mp4" it worked and it saved video to specified location.
Since documentation states that StartRecordingToFileAsync "Writes audio and video content of the current app" it's possible that you can't save just audio using that method.
I've got some troubles with StreamReader.ReadToEndAsync();
//some get response code ...
using (var response = getResponseTask.Result)
{
using (var responseStream = response.GetResponseStream())
{
using (var responseStreamReader = new StreamReader(responseStream))
{
var readToEndTask = responseStreamReader.ReadToEndAsync();
var responseResult = await readToEndTask;
//and some json parse code here
}
}
}
So, when I press the Home button on the device (whatever phone or emulator) while ReadToEndAsync task is in process, result string is not full length on app reactivation... i.e. it's ending just cut out without any exceptions or warning.
As result, I can't parse my json-data to object.
How can I fix it or avoid this situation ?
Thanks everybody in advance!
For this, you need to run your code as a background task. Background tasks will run even your app is deactivated. You can refer : https://learn.microsoft.com/en-us/windows/uwp/launch-resume/support-your-app-with-background-tasks to learn background tasks.
There are two types of background tasks, in process & out process.
I just developed sample UWP app to capture images from web cam. this is working smoothly
this is the code I have used
public class CameraCaptureService : ICaptureService
{
public async Task<StorageFile> CapturePhotoAsync()
{
var dialog = new CameraCaptureUI();
dialog.PhotoSettings.MaxResolution = CameraCaptureUIMaxPhotoResolution.HighestAvailable;
dialog.PhotoSettings.Format = CameraCaptureUIPhotoFormat.JpegXR;
dialog.PhotoSettings.AllowCropping = true;
var file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
...
return (file == null) ? null : file;
}
}
but once after I click Image Capture button
this is awaiting until I confirm If I want to proceed this picture or discard the process and restart (with right sign and incorrect sign)
I'm trying to skip that stage and directly save this to local storage
Is this possible to do, using CameraCaptureUI class PhotoSettings ?
NB : dialog.CaptureFileAsync(CameraCaptureUIMode.Photo); is async method
I'm writing my first Windows Phone 8 app, and I'm just trying something simple. Read / Write file. Here's my two methods:
public static async Task<Week> Load()
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
try
{
StorageFile mealsFile = await folder.GetFileAsync("file.txt");
if (mealsFile != null)
{
using (var stream = await mealsFile.OpenAsync(FileAccessMode.Read))
{
var serializer = new DataContractSerializer(typeof(List<MyTypeHere>));
var w = (List<MyTypeHere>)serializer.ReadObject(stream.AsStreamForRead());
if (w != null)
MyWeek.WeekList = new ObservableCollection<MyTypeHere>(w);
}
}
}
catch(FileNotFoundException fEx)
{
MyWeek = new Week();
}
return MyWeek;
}
public static async Task<bool> Save()
{
try
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile mealsFile = await folder.CreateFileAsync("file.txt", CreationCollisionOption.ReplaceExisting);
using (var stream = await mealsFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (var sw = stream.GetOutputStreamAt(0))
{
var serializer = new DataContractSerializer(typeof(List<MyTypeHere>));
serializer.WriteObject(sw.AsStreamForWrite(), MyWeek.WeekList.ToList());
await sw.FlushAsync();
}
}
MyWeek = null;
return true;
}
catch(Exception ex)
{
return false;
}
}
I'm calling the Save (with breakpoint it works fiine), then call Load (with breakpoint) which load the file, the file exists and it populate my object graph.
When I close the app and restart it, the catch of the FileNotFoundException is caught. Why?
From what I can see the Local Folder is supposed to be persisting the file. What I'm missing that obviously should be obvious...
Thanks
Edit:
I'm using the Windows Phone emulator, and when I close it and hit F5 on Visual Studio, the file is not there anymore.
Apparently by closing the emulator, the files in Local Storage are lost, thanks to #cdndevs via Twitter. I was closing the emulator each time I was stopping debugging instead of letting the emulator simply "stay" there between restart.
By stopping debugging and restarting the app without closing the emulator, the files are there. Well, not super intuitive I must admit, or it might just be me. Hope that help other people like me ;).
I'm trying to share an image through my app, everything works just fine when I run the app on my phone through visual studio, but when I try to run it from my phone, it crashes everytime I click the share button
private async void dataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
args.Request.Data.Properties.Title = "Let's Celebrate";
args.Request.Data.Properties.Description = "It's time to celebrate!";
DataRequestDeferral deferral = args.Request.GetDeferral();
try
{
var finalImg = await GenerateImage();
var folder = Package.Current.InstalledLocation;
const CreationCollisionOption option = CreationCollisionOption.ReplaceExisting;
var file = await folder.CreateFileAsync("letscelebrateshare.png", option);
var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
var pixelBuffer = await finalImg.GetPixelsAsync();
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
(uint)finalImg.PixelWidth,
(uint)finalImg.PixelHeight,
logicalDpi,
logicalDpi,
pixelBuffer.ToArray());
await encoder.FlushAsync();
StorageFile logoFile =
await Package.Current.InstalledLocation.GetFileAsync("letscelebrateshare.png");
List<IStorageItem> storageItems = new List<IStorageItem>();
storageItems.Add(logoFile);
args.Request.Data.SetStorageItems(storageItems);
}
}
finally
{
deferral.Complete();
}
}
private async void bla... [..]
{
Exception exc= null;
try
{
//All your stuff
}
catch(Exception ex)
{
exc = ex;
}
if(exc!=null)
await msg.ShowAsync();
}
Edit: Since I don't use WP in C#. I guess you could try this. Hope this helps ^^
I had the same issue while opening a file open picker. I found a weird solution. When I removed the navigation parameters in every pages and used static variables instead, worked fine for me. I guess this will help you
If the App is there crashing without debugger, try while debugging and the share targets are visible to "suspend and shutdown" ("Lifecycle Events" in visual studio). In most cases you app will then crash because it is suspended and serialize the data.