简体   繁体   中英

Getting data from web service in MvvmCross Xamarin.iOS

I am trying to get JSON from a REST API into Xamarin.iOS. Although I am able to fetch data from API but somehow data is not populated in TableView.

ViewModel

public class SchoolSelectionViewModel : BaseViewModel
{
    private readonly ISchoolNames _schoolService;
    public SchoolSelectionViewModel(ISchoolNames schoolService)
    {
        _schoolService = schoolService;
    }
    public override void Start()
    {
        IsLoading = true;
        _schoolService.GetFeedItems(OnDilbertItems, OnError);
    }

    private void OnDilbertItems(List<SchoolModel> list)
    {
        IsLoading = false;
        Items = list;
    }

    private void OnError(Exception error)
    {
        // not reported for now
        IsLoading = false;
    }

    private bool _isLoading;
    public bool IsLoading
    {
        get { return _isLoading; }
        set { _isLoading = value; RaisePropertyChanged(() => IsLoading); }
    }

    private List<SchoolModel> _items;
    public List<SchoolModel> Items
    {
        get { return _items; }
        set { _items = value; RaisePropertyChanged(() => Items); }
    }
    private MvvmCross.Core.ViewModels.MvxCommand<SchoolModel> _itemSelectedCommand;
    public System.Windows.Input.ICommand ItemSelectedCommand
    {
        get
        {
            _itemSelectedCommand = _itemSelectedCommand ?? new MvvmCross.Core.ViewModels.MvxCommand<SchoolModel>(DoSelectItem);
            return _itemSelectedCommand;
        }
    }

    private void DoSelectItem(SchoolModel item)
    {
        //ShowViewModel<DetailViewModel>(item);
    }
}

Service

public class SchoolNames : ISchoolNames
{
    public SchoolNames()
    {
    }
    public void GetFeedItems(Action<List<SchoolModel>> success, Action<Exception> error)
    {
        var url = "http://demo.imanage-school.com/api/configurations/schoolnames";

        var request = (HttpWebRequest)WebRequest.Create(url);
        try
        {
            request.BeginGetResponse(result => ProcessResponse(success, error, request, result), null);
        }
        catch (Exception exception)
        {
            error(exception);
        }
    }

    private void ProcessResponse(Action<List<SchoolModel>> success, Action<Exception> error, HttpWebRequest request, IAsyncResult result)
    {
        try
        {
            var response = request.EndGetResponse(result);
            using (var stream = response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                var json_data = reader.ReadToEnd();
                json_data = json_data.Replace("\"", string.Empty);
                json_data = json_data.Replace("\\", "\"");

                //if (text.StartsWith("\""))
                //{
                //    text = text.Remove(0, 1);
                //}
                //if (text.EndsWith("\""))
                //{
                //    text = text.Remove(text.Length-1, 1);
                //}
                List<SchoolModel> List = new List<SchoolModel>();

                //List = JsonConvert.DeserializeObject < List <SchoolModel>> text;
                //List = JsonConvert.DeserializeObject(< List < SchoolModel >> text);
                var objects = JsonConvert.DeserializeObject<List<SchoolModel>>(json_data);
                success(List);
            }
        }
        catch (Exception exception)
        {
            error(exception);
        }
    }

    private List<SchoolModel> ParseDilbertItemList(string text)
    {
        var root = JsonConvert.DeserializeObject<SchoolModel>(text);
        var jsondetails = JsonConvert.SerializeObject(text);
        var xml = XDocument.Parse(text);
        var items = xml.Descendants("item");
        var list = items.Select(x =>
                                new SchoolModel()
                                {
            Name = x.Element("title").Value,
            ApiUrl = ExtractHttpImg(x.Element("description").Value)
                                }).ToList();
        return list;
    }

    private string ExtractHttpImg(string value)
    {
        var startPos = value.IndexOf("http://");
        var endPos = value.IndexOf(".gif\"", startPos);
        return value.Substring(startPos, endPos + 4 - startPos);
    }
}

ViewController

public partial class SchoolSelectionView : MvxViewController<SchoolSelectionViewModel>
{
    public SchoolSelectionView() : base("SchoolSelectionView", null)
    {
    }

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();
        this.NavigationController.SetNavigationBarHidden(true,true);

        var source = new MvxStandardTableViewSource(tblSchoolSelection, "TitleText Name");
        this.CreateBinding(source).To<SchoolSelectionViewModel>(vm => vm.Items).Apply();
        this.CreateBinding(source).For(s => s.SelectionChangedCommand).To<SchoolSelectionViewModel>(vm => vm.ItemSelectedCommand).Apply();
        tblSchoolSelection.Source = source;
        tblSchoolSelection.ReloadData();
    }

    public override void DidReceiveMemoryWarning()
    {
        base.DidReceiveMemoryWarning();
        // Release any cached data, images, etc that aren't in use.
    }
}

I feel there is some issue in binding but I am unable to fix it.

Inside your service :

List<SchoolModel> List = new List<SchoolModel>();

//List = JsonConvert.DeserializeObject < List <SchoolModel>> text;
//List = JsonConvert.DeserializeObject(< List < SchoolModel >> text);

var objects = JsonConvert.DeserializeObject<List<SchoolModel>>(json_data);
success(List);

You first create a variable List , then deserialize the JSON, but store it into new variable objects . But you then pass List to the success method, but List is actually empty. You probably want to end with success(objects) to make it work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM