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

Xamarin forms: How to handle notification tap when the app is not in the background?(killed state)

$
0
0

I have implemented push notification on my xamarin forms project(chat application) using Firebase Cloud Messaging. Notification is receiving in all the states and when tapping the notification I need to show the corresponding message listing page.

Notification tapping is working when the app is in the foreground and background modes. But when the app is not present in the background(killed state), tapping is not working. Using DidReceiveRemoteNotification I am handling the notification tap when the app is in the background state. Using WillPresentNotification and DidReceiveNotificationResponse I am showing the notification and handling the notification tap in foreground mode. Codes added below:

 //Notification tapping when the app is in background mode.
 public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
        {
            HandleMessage(userInfo);

            // Print full message.
            LogInformation(nameof(DidReceiveRemoteNotification), userInfo);

            completionHandler(UIBackgroundFetchResult.NewData);

            var myData = JsonConvert.DeserializeObject<List<webContentList>>(userInfo[new NSString("webContentList")] as NSString);
            Console.WriteLine($"myData received: {myData}");
            if (UIApplication.SharedApplication.ApplicationState.Equals(UIApplicationState.Active))
            {
                //App is in foreground, no action
            }
            else
            {
                MessagingCenter.Send<object, List<webContentList>>(this, "messagedata", myData);
            }
        }

        //Showing the notification when the app is in the foreground mode.
       [Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")]
        public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification,
Action<UNNotificationPresentationOptions> completionHandler)
        {
            completionHandler(UNNotificationPresentationOptions.Sound | UNNotificationPresentationOptions.Alert);
        }

        //Notification tapping when the app is in the foreground mode.
[Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")]
            public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action
            completionHandler)
            {
                completionHandler();
                NSDictionary userInfo = response.Notification.Request.Content.UserInfo;
                var myData = JsonConvert.DeserializeObject<List<webContentList>>(userInfo[new NSString("webContentList")] as NSString);
                Console.WriteLine($"myData received: {myData}");
                MessagingCenter.Send<object, List<webContentList>>(this, "messagedata", myData);
            }

FinishedLaunching

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            LoadApplication(new App());

            #region Push Notification            
            Firebase.Core.App.Configure();

            // Register your app for remote notifications.
            if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
            {
                // iOS 10 or later
                var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
                UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) => {
                    Console.WriteLine(granted);
                });

                // For iOS 10 display notification (sent via APNS)
                UNUserNotificationCenter.Current.Delegate = this;

                // For iOS 10 data message (sent via FCM)
                //Messaging.SharedInstance.RemoteMessageDelegate = this;
            }
            else
            {
                // iOS 9 or before
                var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
                var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);
                UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
            }

            UIApplication.SharedApplication.RegisterForRemoteNotifications();

            Messaging.SharedInstance.Delegate = this;
            Messaging.SharedInstance.ShouldEstablishDirectChannel = true;
            #endregion

            return base.FinishedLaunching(app, options);
        }

My notification body: webContentList is my model data.

{
 "to" : "dmtfiSvBBM0:APA91bFnHkamMSYgxPuiSfdvKnU8hD_mOqrWijnENNgXVSkSgo1ILH3-uKVCU7Ez2PXXOhtDoobIyKBf5UshVfTmvjSqHgXMRTsqguKCSTjIfGnXrVP-_cNFq2sisshZO-BcfkwKTl-I",
 "collapse_key" : "type_a",
 "notification" : {
      "body" : "This is body",
     "title": "Tech Team",
     "priority":"high",
     "content_available":true
 },
 "data" : {
    "webContentList": [
        {
            "webContentDefinitionId": 818084,
            "pageTitle": "CCD Grade 3-4",
            "pageKwd": "CCD Grade 3-4",
            "pageDesc": "CCD Grade 3-4",
            "siteId": 45,
            "pageCreatedTime": 1555145959428,
            "pageUpdatedDate": 1555927274279,
            "modifier": {
                "userId": 12944,
                "applicationId": 32,
                "username": "robert.downey",
                "email": "robert@master-mail.net",
                "firstName": "Robert",
                "lastName": "Downey"
            },
            "creator": {
                "userId": 12944,
                "applicationId": 32,
                "username": "robert.downey",
                "email": "robert@master-mail.net",
                "firstName": "Robert",
                "lastName": "Downey"
            }
        }
        ]
 },
  "ttl": 3600
}

Issue

When the app is in the killed state only the home page is loading, not showing the message listing page. But before showing the home page in the UI, the message listing show progress(acr userdialogs) is also present in the UI. So I think LoadApplication(new App()); in FinishedLaunching is working after the notification tap function when the app is in the killed state. So how I can stop the execution of the normal app launching code and show the message listing page when the app is in the killed state?


Custom URL schema in Xamarin.Forms for Android

$
0
0

Hello dear people here. I got an issue with one of my Xamarin.Forms apps. I want to register for a custom URL scheme. Its working fine under iOS but not so much under Android.

As far as i can see the only thing i need to do is to use the following attribute in my MainActivity:
[IntentFilter(new[] { Android.Content.Intent.ActionView }, DataScheme="mycustomurl", Categories = new[] { Android.Content.Intent.CategoryBrowsable, Android.Content.Intent.CategoryDefault })]

Afterwards i should receive the data whenever some URL with the scheme mycustomurl (ie: mycustomurl://do/whatever/i/want) is found. I am using the camera with an QR-Code to test my registration. Am i doing something wrong? The xamarin.forms documentation about app linking says that the DataScheme should be either http or https. But the Android docs do not state that you must choose between those 2.

Am i missing something?

Best regards
Michael

call native method from PCL failing Xamarin.From > 4

$
0
0

When trying to call a native method from my Shared Project (.NET Standard 2.0) to my iOS project. It not entering the CallToNativeMethod on my iOS project when using Xamarin.Forms version 4 or up. I followed this structure:

Shared Project

//Namespace 
//YourClass
public event EventHandler CallToNativeMethod;

public void RaiseCallToNativeMethod()
{
    if (CallToNativeMethod != null)
        CallToNativeMethod(this, new EventArgs());
    // C# 6 way (Does the same thing as the line above, but looks cleaner)
    // CallToNativeMethod?.Invoke(this, new EventArgs());
}

iOS / Android /etc. Renderer

//Namespace
//ClassOfRenderer
//Inside your OnElementChanged Method
((YourClass)Element).CallToNativeMethod += (sender, e) =>
{
    Control.YourNativeMethodIsCalledHere();
}

Back in Shared Project

var yourClass = new YourClass();
yourClass.RaiseCallToNativeMethod();

But the issue is that is not firing this part on the iOS Rendered:

  ((YourClass)Element).CallToNativeMethod += (sender, e) =>
    {
        Control.YourNativeMethodIsCalledHere();
    }

Do i need to do something different? Its working on Xamarin.Forms 3.6.0.539721

HttpClient/API calls really slow.......( Only on iOS ) Andoird and UWP are good

$
0
0

On Android and UWP, everything is good.

However ONLY for iOS the code just runs/executes really slow. Any ideas?

var uri = new Uri(url);

using (var client = new HttpClient())
{
    var request = (HttpWebRequest)WebRequest.Create(uri);
    request.ContentType = "application/json";
    request.Method = "POST";
    request.ServerCertificateValidationCallback += (s, cert, chain, err) => true;
    request.Headers.Add("Authorization", "Bearer " + accessToken);

    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        streamWriter.Write(json);
        streamWriter.Flush();
        streamWriter.Close();
    }

    // Connect with Server
    var response = (HttpWebResponse)request.GetResponse();

    // Response
    switch (response.StatusCode)
    {
        case HttpStatusCode.Accepted:
        case HttpStatusCode.OK:
            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                var read = streamReader.ReadToEnd();
            }
            break;
    }
}

Data Annotation Validation from .net Standard Class Library

$
0
0

Hi Team,

I have class library in .net Standard 2.0 with EntityFrameworkCore. I have created class with Custom Data Annotation as below:

Model Definition

public class UserLogin : NotificationObject
{
[DbRequired]
[Display(Name = "USER NAME", Prompt = "ENTER USER NAME")]
public string User_Name
{
get { return GetValue(() => User_Name); }
set { SetValue(() => User_Name, value); }
}

    [Display(Name = "PASSWORD", Prompt = "ENTER PASSWORD")]
    [DataType(DataType.Password)]
    [DbRequired]
    public string User_Password
    {
        get { return GetValue(() => User_Password); }
        set { SetValue(() => User_Password, value); }
    }
}

**But this data annotation validation is working in Asp.Net Core and WPF. But we want to use the same in Xamarin.Forms for Android & iOS and UWP. Is it possible or any workaround? As I heard that in .net Standard you need write once and can be reuse in all other environment **

How to display Gregorian date in DatePicker instead of Hijri when culture is Arabic?

$
0
0

My app is dual-language, English and Arabic, and when the culture is set to Arabic the date shows as Hijri. How can I force the datepicker to show the Gregorian date?

Why do I still need a googlemaps API key when I am creating a custom map?

$
0
0

I'm am using xamarin forms maps.
So I am creating a custom render for android that will pull tiles from a tile server such that I do not need to use google for maps.
I have used the following aloisdenielDOTgithubDOTio/xamarin-forms-custom-maps/
help create my custom render.

I notice that without an API key, it does not pull tiles from my tile server and it just a blank page.
With an API key it will pull tiles from my tile server.

I do not want to use a google API key with my custom map, is there a workaround for this?

How to binding property in a behavior?

$
0
0

In xaml file:

<Picker 
        x:Name="picker_cadastronotificacao_tipotelefone" 
        Title="{x:Static local:AppResources.picker_cadastronotificacao_tipotelefone}"
         Style="{StaticResource Picker}"
         SelectedItem="{Binding TipoTelefoneSelecionado}">
        <Picker.Items>
                  <x:String>Celular</x:String>
                  <x:String>Telefone Fixo</x:String>
         </Picker.Items>
</Picker>

<Entry 
      x:Name="entry_cadastronotificacao_telefone" 
      Placeholder="{x:Static local:AppResources.entry_cadastronotificacao_telefone}" 
      Style="{StaticResource EntradasTexto}" 
      Text="{Binding Telefone}"
      Keyboard="Telephone"
      IsEnabled="{Binding HabilitarCampoTelefone}">

      <Entry.Behaviors>
             <behavior:MaskBehavior Mascara="{Binding MascaraTelefone}"/>
      </Entry.Behaviors>
</Entry>

In view model:

if (TipoTelefoneSelecionado == "Telefone Fixo")
      MascaraTelefone = "(XX) XXXX - XXXX";
else if(TipoTelefoneSelecionado == "Celular")
      MascaraTelefone = "(XX) XXXXX - XXXX";

Error: No property, bindable property, or event found for 'Mascara', or mismatching type between value and property.


Is there any way to access the native control in Xamarin.Forms at runtime?

$
0
0

For instance in NativeScript I can

myControl.ios. // Access the native control
myControl.android. // Access the native control

anywhere.

Is there any way to access the native control in Xamarin.Forms at runtime and manipulate it?

How to get a parameter from MainActivity via DependencyService?

$
0
0

Hi!
I'm working with DependencyServie. Some method must implement in MainActivity and return a List result
How to get that List result from MainActivity via DependencyService?
Thank you!

Having trouble getting BackgroundFetch to work in Xamarin Forms iOS.

$
0
0

Hi,
I've been working on this for days now. I run our XF iOS app on a real device in debug mode. After it starts up, I press Home and the app goes to sleep - a debug statement in OnSleep tells me it got there. Next, I leave it alone and watch for the debug statement that tells me it got to PerformFetch. After 18 hours it still did not appear.
I know that iOS controls when it does a PerformFetch. But seriously, 18 hours and nothing?
Could iOS have messed up its timer or the minimum time for our app? Is there a way to reset it or does that happen when I reload a newly compiled version? Or do I have to change the actual version number?

For those that have read this far, you probably have some questions. Here are my settings and some snippets of my code.

In Info.plist, in Background Modes, I selected Enable Background Modes and Background Fetch.

On the device:
1) in Settings, I enabled BackgroundAppRefresh for the app.
2) In Settings, under the app, I enabled BackgroundAppRefresh

`
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{

UIApplication.SharedApplication.SetMinimumBackgroundFetchInterval(UIApplication.BackgroundFetchIntervalMinimum);
}

public override async void PerformFetch(UIApplication application, Action<UIBackgroundFetchResult> completionHandler)
{
try
{
    var result = UIBackgroundFetchResult.NoData;
        bool bOK = await Util.RequestProjectsFromWebService(user);        
    result = UIBackgroundFetchResult.NewData;
        }
        catch (Exception ex)
        {
    result = UIBackgroundFetchResult.Failed;
        }
        finally
        {
               completionHandler(result);
        }

}
`
I'll be away for a few days, so it will be interesting to see how the app performs during that time.

Any ideas on how to get into PerformFetch would be much appreciated.
Regards,
Will

CarouselView implementation, CardsView nuget package

How to Authenticate an user using ADFS in xamarin forms?

$
0
0

Hi All,

I am new to xamarin forms. I need to authenticate the users using ADFS. Please guide me what are all prerequisite needed and how to achieve this ?

How can I set and get a selected value in my custom picker? The value is not changeable

$
0
0

How can I get the selected item of my custom picker? It always goes back to the initial state
I tried in several ways and I only had to question.

 public class MyDelegate : UIPickerViewDelegate
    {
        List<string> sourceList = new List<string>();
        public MyDelegate(List<string> list)
        {
            sourceList = list;
        }
        public override void Selected(UIPickerView pickerView, nint row, nint component)
        {
            UILabel label = new UILabel();
            label.Text = sourceList[(int)row];
        }

        public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view)
        {

            try
            {

                UIView contentView = new UIView(new CGRect(0, 0, UIScreen.MainScreen.Bounds.Size.Width, 80));

                UILabel label = new UILabel();
                label.Frame = contentView.Bounds;
                contentView.AddSubview(label);
                label.Text = sourceList[(int)row];
                label.Lines = 4;
                label.TextAlignment = UITextAlignment.Center;
                //Change the label style
                label.Font = UIFont.SystemFontOfSize(20);
                label.LineBreakMode = UILineBreakMode.TailTruncation;
                return contentView;

            }
            catch (Exception ex)
            {

                throw;
            }

            //return base.GetView(pickerView, row, component, view);
        }
        public override nfloat GetRowHeight(UIPickerView pickerView, nint component)
        {
            return 80;
        }
    }
}


   public class CustomPickerRenderer : PickerRenderer
    {
        List<string> itemList = new List<string>();
        protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
        {
            base.OnElementChanged(e);
            var element = (CustomPicker)this.Element;
            Picker picker = Element;
            //itemList = picker.Items.ToList();       
                UITextField uITextField = new UITextField();
                uITextField = Control;
                UIPickerView uIPickerView = uITextField.InputView as UIPickerView;       

            if (this.Control != null && this.Element != null && !string.IsNullOrEmpty(element.Image))
            {
                var downarrow = UIImage.FromBundle(element.Image);
                Control.RightViewMode = UITextFieldViewMode.Always;
                this.Control.BorderStyle = UITextBorderStyle.None;
                Control.LeftView = new UIKit.UIView(new CGRect(0, 0, 5, 0));
                Control.LeftViewMode = UIKit.UITextFieldViewMode.Always;
                Control.BorderStyle = UITextBorderStyle.None;
                Control.RightView = new UIImageView(downarrow);
            }
        }
    }
}

Xam.Plugins.Notifier: Android Tap in Xamarin.Forms.Shell

$
0
0

Using Xam.Plugins.Notifier for Local Notifications I am able to show a notification in Android. However, when I tap the notification, it reloads the application. Similar to how a remote notification would.

I handle the OnNewIntent() in the MainActivitiy.cs but it never fires.

How do I tap a Local Notification made by Xam.Plugins.Notifier so that OnNewIntent() fires and I can show a Shell item?

    protected async override void OnNewIntent(Intent intent)
    {
        base.OnNewIntent(intent);
        var title = intent.GetStringExtra("title");
        if (title != null)
        {
            await Shell.Current.GoToAsync("Tools/Sales");
        }
    }

How can i make a label fit/ auto size the grid row and column specified for it?

$
0
0

Hi,
I am using Grid layout to try making the app responsive and when i use label and set a font size to it, the label sometimes surpasses the space (grid.row & grid.colum) alocated for it.

Is it possible to make the label always fit the alocated space ?

<Grid RowSpacing="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="3.5*"/>
                <RowDefinition Height="6.5*"/>
            </Grid.RowDefinitions>
            <Grid Grid.Row="0" Grid.Column="0">
                <Image x:Name="imagemNav" Grid.Row="0" Grid.Column="0" Source="{local:ImageResource KiaiDay.Images.navigationImage.png}" Aspect="Fill"
                    HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"/>
                <Grid Padding="20,10,20,0" ColumnSpacing="0" RowSpacing="0">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="3.5*"/>
                        <RowDefinition Height="4.5*"/>
                        <RowDefinition Height="2*"/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="6*"/>
                        <ColumnDefinition Width="4*"/>
                    </Grid.ColumnDefinitions>

...
                    <StackLayout Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2" Spacing="4">
                        <Label Text="Some text" FontSize="50" TextColor="White" FontFamily="{ StaticResource RegularFont}" Margin="20,0,0,0"/>
                        <Label Text="Some other text" FontSize="20" TextColor="White" FontFamily="{ StaticResource LightFont  }" Margin="25,-10,0,0"     
                                    Opacity="0.7"/>
                    </StackLayout>
...
</Grid>

How to change the name of app(In the screen, under the icon)

$
0
0

Hi guys,

I am building an app in Xamarin.Forms. I want to change the name of app, both iOS and Android. I tried to change the information in mainactivity.cs and Androidmanifest. However it is not working. I also don't know how to do it in iOS.

Would you please to help me?

Thank you very much.

Firing method in the View when a property in the ViewModel changes

$
0
0
Hi all,
As the title says I would like to call a method in my View when a property in my ViewModel changes. I was wondering if this is possible to do it by using the INotifyPropertyChanged interface or if I should implement the observer - observable pattern on my own for this particular task.

Practical example: I have a StackLayout in the View and an integer property called number in the ViewModel, I want to call a method in the View which makes sure there are exactly n (where n is the value of number) entries in the StackLayout every time number changes.

Note: number is the output of a calculation in the model and it doesn't have to appear anywhere in the view.

Thanks to everyone in advance.

How to set vertical align icon of the selected tab in a tabbedpage

$
0
0

Hi everyone, the icon of the selected tab aligns top vertically. How to set that alignment to center like others unselected tabs?

I am using FreshMVVM Framework and this is the code:

var masterDetailsMultiple = new MasterDetailPage();
masterDetailsMultiple.Title = "Master";
var menuPage = FreshPageModelResolver.ResolvePageModel();
masterDetailsMultiple.Master = menuPage;

var tabbedNavigation = new FreshTabbedNavigationContainer();
tabbedNavigation.On<Xamarin.Forms.PlatformConfiguration.Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);
tabbedNavigation.AddTab("", "update2.png", null);
tabbedNavigation.AddTab("", "form2.png", null);
tabbedNavigation.AddTab("", "poll2.png", null);
tabbedNavigation.AddTab("", "star2.png", null);
tabbedNavigation.AddTab("", "ideas2.png", null);

Problems when collapsing listview element in iOS

Viewing all 91519 articles
Browse latest View live


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