Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all 89864 articles
Browse latest View live

Update Progressbar + Label from iOS NSUrlSession Background-Download freezes UI

$
0
0

Hey guys!
I already put many hours into researching the following problem:

I have a ContentPage in my PCL-project which consists of a ProgressBar and a Label. Both should display the progress of a download running in a background task. Therefore I'm using the MessageCenter to subscribe to a channel on which I publish the current download's progress (DownloadProgressMessage).

Additionally, I have a ViewModel which holds two Properties (double DownloadProgress, string DownloadText) which are binded to the ProgressBar + Label. When I receive a new DownloadProgressMessage I update the Properties accordingly within the ViewModel so the displayed values get updated. The messaged are sent from the DidWriteData() method in my NSUrlSessionDownloadDelegate. When I run the app from VS (Debug OR Release) everything works just fine. The download starts, progressbar and label get updated. When I switch to another app and get back into mine, all values got updated accordingly. Now comes the strange part:

When I force stop the app and start it again from the homescreen of the iPad, switching to another app and coming back results in an UI-freeze. The values are stuck on the state where I left the app, but the download continues in the background. I can't debug the problem because it only appears if the app is not "connected" to VS.

Property example (using GalaSoft.MvvmLight):

private double _progressValue;
public double ProgressValue
{
    get => _progressValue;
    set { Set(ref _progressValue, value); }
}

Message subscribe in ViewModel:

MessagingCenter.Subscribe<DownloadProgressMessage>(this, "DownloadProgressMessage", message => {
    ProgressValue = message.Percentage;
    ProgressText = "downloading".Translate() + " " + message.Percentage + "% " + "percent_of".Translate() + " " + ((message.TotalBytesExpectedToWrite / 1024f) / 1024f).ToString("#0.##") + " MB";
});

DidWriteData from the NSUrlSessionDownloadDelegate:

public override void DidWriteData(
            NSUrlSession session,
            NSUrlSessionDownloadTask downloadTask,
            long bytesWritten,
            long totalBytesWritten,
            long totalBytesExpectedToWrite)
{
    // Debug.WriteLine($"{requestUri}:{percentage}%");

    var message = new DownloadProgressMessage()
    {
        BytesWritten = (long)totalBytesWritten,
        TotalBytesExpectedToWrite = (long)totalBytesExpectedToWrite,
        Percentage = totalBytesWritten * 100 / totalBytesExpectedToWrite
    };
    MessagingCenter.Send(message, "DownloadProgressMessage");

}

Does anyone have an idea why this is happening and more important, why it only happens when the app is not "connected" to VS?

Thanks in advance!


Same listview item not getting selected after pressing back

$
0
0

I have a listview which on any item selected navigates to another XAML page. When I press the back button I return back to the original listview page.

Now if I select the same list view item, it does not navigate to the intended XAML page. If I select another item in listview it navigates.

So the issue I am facing is that tapping/selecting the same item does not navigate to the intended page the second time after the back button is pressed, but any other item in the list does navigate. Also the break point is not hit in VS (onitemtapped event args), so can't debug the issue too.

Any help/suggestions on the same?.

Thanks In Advanvce!!..

Shell custom renderer how to set bottom navigation animations disable?

$
0
0

Android and ios Shell renderer how to set bottom navigation animations disable?

Xamarin Forms IOS - NSData from a json string

$
0
0

I'm trying to get an NSData from a json string, to use it later to create an MGLShape (From Mapbox SDK) like this:

MGLShape.ShapeWithData(jsonData, 4, out error); //jsonData is the NSData, 4 is the nuint for the type of encoding and ou error is a plain NSError.

But i'm not able to serialize the json string into NSData using NSJsonSerialization, the json string is corrected and validated before, (but when i use an NSString from the string, it adds an extra pair of brackets "{ //json }", which i can remove before trying the NSJsonSerialization, here is how i'm trying to achive my goal:

string jsonSerialized = JsonConvert.SerializeObject(fc);//Valid Json
NSString json = new NSString(jsonSerialized);//Adds the extra pair of brackets
NSData jsonData = NSJsonSerialization.Serialize(json, NSJsonWritingOptions.SortedKeys, out error);

But it gives me the following error:

Foundation.MonoTouchException: Objective-C exception thrown.  Name: NSInvalidArgumentException Reason: *** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write

This error happens with, or without the extra pair of brackets (removed the first and last chars from the NSString), here is a shortned version of my json:
(i used https://jsonformatter.curiousconcept.com/ to test the json)

{"type":"FeatureCollection","crs":null,"features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[-9.000000,38.000000]},"properties":{"id":1,"icon":"MyIcon.png"}}]}

What am i doing wrong here? how can i parse an json string into an NSData?

Can the title view background color be line gradient color in Xamarin.forms?

$
0
0

I want to make the TitleView's background color be gradient color like this:

How to do it ?

or need I use a custom control?

How to apply pagination in lisview using Xamarin forms cross platform?

$
0
0

How to apply pagination in lisview using Xamarin forms cross platform? Please help.I have searched on google but couldn't find the solution.
Thanks in advance

Error in android url scheme

$
0
0

Hi

I'm trying to make custom URL Scheme In Android

When I create a new xamarin forms app and add this code to manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.app7">
    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
    <application android:label="App7.Android">
         <activity  android:name="com.companyname.app7.MainActivity">
          <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="myapp" />
          </intent-filter>
        </activity>
     </application>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

And I call the app by clicking a link

<a href="myapp://hello-world"> Circle Here</a>

I get this error

Java.Lang.RuntimeException: 'Unable to instantiate activity ComponentInfo{com.companyname.app7/com.companyname.app7.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.companyname.app7.MainActivity" on path: DexPathList[[zip file "/data/app/com.companyname.app7-1/base.apk"],nativeLibraryDirectories=[/data/app/com.companyname.app7-1/lib/arm, /data/app/com.companyname.app7-1/base.apk!/lib/armeabi-v7a, /vendor/lib, /system/lib]]'

OIDC Client Logout

$
0
0

I am following the example to authenticate a user by using this sample:
https://github.com/IdentityModel/IdentityModel.OidcClient.Samples/tree/master/XamarinForms

I have the login working, it authenticates and closes the ChromeTabBrowser and redirects back to my app screen because of the RedirectURI setting, but this sample online doesn't have an example for the Logoff functionality. How would I do the same, Logoff, and then have it close the ChromeTabBrowser and redirect back to my app, I have set the same URI I am using for login, to the PostLogoutRedirectURI property in the OidcClientOptions, but no luck.

public static OidcClientOptions SetAuthOptionsPostLogout()
{
var browser = DependencyService.Get();

        return new OidcClientOptions
        {
            Authority = GlobalSetting.Instance.AuthAuthorityURI,
            ClientId = GlobalSetting.Instance.AuthClientID,
            Scope = GlobalSetting.Instance.AuthScope,
            RedirectUri = GlobalSetting.Instance.AuthReturnURI,
            PostLogoutRedirectUri = GlobalSetting.Instance.AuthReturnURI,                               
            Browser = browser,
            ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect
        };
    }

and my call to logout is:

public ICommand Logout => new Command(async () =>
{
try
{
LoadingMessage = "Logging Off...";
IsBusy = true;

            var options = AuthService.SetAuthOptionsPostLogout();
            Client = new OidcClient(options);
            await Client.LogoutAsync();

            //DELETE OTHER SETTINGS HERE

            IsBusy = false;
            await _Navigation.PushAsync(new Login());
        }
        catch (Exception ex)
        {
            IsBusy = false;
            await ex.TrackAndShowAlert("VM", "Logout");
        }
    });

The authentication service logs me off, but that window never closes, so in the app, the spinning "Logging Off..." is still active awaiting the call.


iOS Binding Unity as a library

$
0
0

Hi all,

I don't even know where to start :D

Since alpha 2019.3 Unity offers the feature "Unity as a Library" https://blogs.unity3d.com/2019/06/17/add-features-powered-by-unity-to-native-mobile-apps/ which I'm currently trying to integrate into one of our Xamarin Apps.
There are descriptions how to do that natively for Android and iOS which I got both working fine.
Just for reference:
https://forum.unity.com/threads/integration-unity-as-a-library-in-native-ios-app.685219/
https://forum.unity.com/threads/integration-unity-as-a-library-in-native-android-app.685240/
This is actually a really big deal so it is great working on it :D

However, I got it working fine for Xamarin Android. Now I'm trying on iOS which appears to be much more complicated.

The unity project will be exported as a native Objective-C++ framework (I think at least as there are .mm files using Objective C)
When using Sharpie to bind the framework I get a super large APIDefinitions file.
After some research I figured out that I have to define a scope to the Headers of the Framework, then the APIDefinitions are in fact much smaller and only reference the header files.

Now to my (current) problem:

If I open the ApiDefinitions then there is an interface UnityFramewok which comes from the UnityFramework.h file.
But this header holds a reference to a class UnityView which is not part of the headers. It is within the framework( at least it is within the Library project in Xcode so I assume it is bundled into the framework.)
I copied the .framework into the bindings Native References but I can't see any actual change happening when I do that.
The UnityView can not be found within the interface and I also can't import it from the library because the native reference is not available.

So how can I reference to a class of the framework from within an interface that is defined in the ApiDefinitions?

Thank you already!

Xamarin.Forms Shell - when a ContentPage is destroyed?

$
0
0

Am having a Xamarin.Forms Shell application. On the main page I have a list of some objects and on a button click I navigate to a detail page (DetailPage class) like this:

Shell.Current.GoToAsync(url_to_detail_page?id=X);

New instance of DetailPage is created and properly displays object X.

I navigate back to main page.

I click the button to navigate again to a detail page (another object with another ID):
Shell.Current.GoToAsync(url_to_detail_page?id=Y);

New instance of Detailpage is created and properly displays object Y.

But at this moment both DetailPage instances (X and Y) obviously still exists. The DetailPage subscribes to an MessagingCenter event and once this message is sent it is triggered on both X and Y instances of the page.

**Is this normal that the ContentPage is not destoyed when navigating back from it? **

Handling the MessagingCenter event takes some time and I don't want to run it multiple times... I can handle that somehow but it would be a workaround. I would prefer the DetailPage to be destroyed as it is no longer needed.

thansk

Jiri

MVVM: how to update an item inside a lstview with the text property of a button in the same lstview

$
0
0

Hi. Sorry if my English is rough, Spanish is my native language.

  1. I'm using MVVM.
  2. I have a collection of items inside a listview and each one has 2 buttons.
  3. Button.Text property is variable. It is the result of a convertion based on a property of the collection item.
  4. Both buttons use the same command.

I want to update the collection item with the random Button.Text generated in the convertion. How can I do that?

// =============================
//Model.cs

public class SomeClass 
{
    public string ItemType {get;set;}
    public string ButtonTextProperty {get;set;}
}
// =============================

// =============================
// ViewModel.cs

public Command SomeCommand { get; set; }

public ControlObjetosChecklistsViewModel()
{
    this.SomeCommand = new Command(async (object param) => await someCommand (param));
}

private async Task someCommand(object param)
{
    // get the object by taking the button bindingcontext
    // get button text property
    // update object with that text property
}
// =============================

// =============================
//View.xaml
<ListView x:Name="listView" ItemsSource="{Binding ItemSource}" SelectionMode="None" HasUnevenRows="True">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                                        <Button x:Name="btn1" 
                                                Text="{Binding ItemType, Converter={StaticResource converter}, ConverterParameter=converterparameter1}" 
                                                Command="{Binding Source={x:Reference listView}, Path=BindingContext.SomeCommand}" 
                                                CommandParameter="{Binding .}" 
                                                HorizontalOptions="FillAndExpand"/>
                                        <Button x:Name="btn2" 
                                                Text="{Binding ItemType, Converter={StaticResource converter}, ConverterParameter=converterparameter2}" 
                                                Command="{Binding Source={x:Reference listView}, Path=BindingContext.SomeCommand}" 
                                                CommandParameter="{Binding .}"   
                                                HorizontalOptions="FillAndExpand"/>
                                    </StackLayout>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
</ListView>
// =============================

Convert a byte array to a Image on Forms.

$
0
0

So, i saw many examples here and i am trying to adapt to my code ! But, when appears the image, comes blank... i am a newbie, so... lol
I just want to show the image after click on the button !! Is not to save on the smartphone.

The .cs code:

ApiCall apiCallFoto = new ApiCall();
            ImageSource imagem = null;

            btnFoto.Clicked += async (sender, e) =>
            {
               await apiCallFoto.GetFoto<byte[]>("Nomes", "Foto", envolvID).ContinueWith(t =>
                {
                    //Aqui verificamos se houve problema ne requisição
                    if (t.IsFaulted)
                    {
                        Debug.WriteLine(t.Exception.Message);
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            DisplayAlert("Falha", "Ocorreu um erro na Requisição :(", "Ok");
                        });
                    }
                    //Aqui verificamos se a requisição foi cancelada por algum Motivo
                    else if (t.IsCanceled)
                    {
                        Debug.WriteLine("Requisição cancelada");

                        Device.BeginInvokeOnMainThread(() =>
                        {
                            DisplayAlert("Cancela", "Requisição Cancelada :O", "Ok");
                        });
                    }

                    //Caso a requisição ocorra sem problemas, cairemos aqui
                    else
                    {
                        //Se Chegarmos aqui, está tudo ok, agora itemos tratar nossa Lista
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            byte[] fotoBytes = t.Result;
                           // Image image = new Image();
                            imagem = ImageSource.FromStream(() => new MemoryStream(fotoBytes));


                            Navigation.PushAsync(new FotoEnvolvido(imagem));

                        });

                    }
                });
            };

The FotoEnvolvido.cs :

public partial class FotoEnvolvido : ContentPage
    {
        private ImageSource imagem;

        public FotoEnvolvido(ImageSource imagem)
        {
            InitializeComponent();
            this.imagem = imagem;
            BindingContext = imagem;

        }
    }

The FotoEnvolvido.xaml :

<Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="*"/>
      <RowDefinition Height="100"/>
    </Grid.RowDefinitions>
    <Image Source="{Binding imagem}" x:Name="fotoperfil"/>

</Grid>

How to change the TitleColor in the TitleView in Xamarin.Forms.Shell?

$
0
0

is it Shell.TitleColor property? I set it to white but nothing changed.

How do I do repeated pinch gestures on the iOS simulator?

$
0
0

The multi-touch function on the Xamarin iOS simulator is great but I have bumped into what I hope is a silly (i.e. me being dense) problem. When I do a pinch, the two finger circles obviously have to go closer together. When they get as close as they can go, is there a way to move them apart again so that I can do another pinch gesture?

I have tried switching to Shallow Press and back to Multi-Touch but the circles stay where they were last left.

Any way to detect when user closed browser opened with Browser.OpenAsync?

$
0
0

Using the following to open an in-app browser:
await Browser.OpenAsync("https://visualstudio.microsoft.com/", BrowserLaunchMode.SystemPreferred);

Is there a way to detect when user press X or Done and comes back to the app?


Xamarin Forms: Is it possible to save and retrieve an EpubBook data using SettingsPlugin?

$
0
0

I am using SettingsPlugin for saving values to local DB. Using this plugin I have saved an EpubBook data like below:

CrossSettings.Current.AddOrUpdateValue("epub", epubBook.ToString());

Retrieved the value like below:

string epubString = CrossSettings.Current.GetValueOrDefault("epub", string.Empty);
if (!string.IsNullOrWhiteSpace(epubString))
{
    //Need to convert string epub data to EpubBook data
}

I need to convert the string epub data to EpubBook? Is this possible? This is for caching the EpubBook data.

I have done the same using Application.Current.Properties and saving and retrieving is working fine there. Please see below code:

//Saving value
Application.Current.Properties["epub"] = epubBook;
//Retriving value
EpubBook epubBook = (EpubBook)Application.Current.Properties["epub"];

But the Application.Current.Properties values are clearing automatically after closing the app. That's why I start working on SettingsPlugin. So is there any way to save and retrieve an EpubBook using SettingsPlugin? If no suggests a way to caching the EpubBook data?

UseSafeArea not working correctly

$
0
0

I have a CollectionView, which contains a CollectionView, which contains a FlexLayout.
The top CollectionView is being used as a Carousel to contain the other CollectionViews.

When I use ios:Page.UseSafeArea="true", it does not handle adding the additional safe area correctly.

If I turn the iPhone to landscape mode, with the notch on the right, then the right edge of the FlexLayout is cut off by the safe area. The left edge starts at the safe area as it should.

It's as if the FlexLayout does not realize that the area it is to be drawn into, has been made shorter by UseSafeArea.

So what is going on and how do I fix it?

shell tabbar double click problem?

$
0
0

on shell tabbar I have problem that color state is changing when I click double , have to be one click only why you think this problem? Thanks

How to Scroll A grid

$
0
0

I created a grid of buttons in XAML. in portrait mode it works great. in landscape, there is not enough space for all the buttons.
How can I allow the grid to scroll so that all the buttons would be visible and selectable?
Here is the XAML:
<ContentPage.Resources>

        <Style x:Key="ButtonSettings" TargetType="Button">
            <Setter Property= "VerticalOptions" Value="Center" />
            <Setter Property= "BackgroundColor"  Value= "Orange"/>
            <Setter Property= "TextColor" Value="Black" />
            <Setter Property= "FontSize" Value="Large"  />
            <Setter Property= "BorderRadius" Value="10"/>
            <Setter Property= "BorderWidth" Value="2"/>
            <Setter Property= "BorderColor" Value="Black"/>
            <Setter Property= "HorizontalOptions" Value="Center"/>
        </Style>

    </ResourceDictionary>
</ContentPage.Resources>

<ContentPage.BindingContext>
    <local:MainPageViewModel />
</ContentPage.BindingContext>

<Grid BackgroundColor="Chocolate">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height=".5*" />
        <RowDefinition Height=".5*" />
        <RowDefinition Height=".5*" />
    </Grid.RowDefinitions>

........

Can Liquid swipe be done in Xamarin.forms?

$
0
0

as the animation is very cool and can be done in flutter.

image
can it be done in Xamarin?

Viewing all 89864 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>