[英]Xamarin.Forms DependencyService always returns null
Hej, 喂
im trying to load some data from the native iOS project using the Dependency Service. 我试图使用Dependency Service从本地iOS项目加载一些数据。
Its a simple task im trying to desirialize some Data that i had saved before, but regardless what i do it always returns null. 它是一个简单的任务,试图对我之前保存的某些数据进行反序列化,但是无论我做什么,它总是返回null。
If i check the values with the debugger in iOS project theyre never null. 如果我在iOS项目中使用调试器检查值,则它们永远不会为null。 Very strange maybe im missing something ... 很奇怪,也许我错过了一些东西...
My Interface Implementation: 我的界面实现:
[assembly: Xamarin.Forms.Dependency(typeof(SaveRead))]
namespace LindeXF.iOS {
public class SaveRead : ISaveRead {
public async Task<ApplicationModel> LoadApplicationModel(string userName) {
try {
var userPath = CreatePathJson(userName);
if (File.Exists(userPath)) {
await Task.Run(() => {
using (var file = File.OpenText(userPath)) {
var serializer = new JsonSerializer();
var m = (ApplicationModel) serializer.Deserialize(file, typeof(ApplicationModel));
}
});
}
}
catch (Exception ex) {
throw new Exception(ex, "LoadApplicationModel()");
}
return new ApplicationModel {Username = userName};
}
}
in the Portable Project 在便携式项目中
DependencyService = Xamarin.Forms.DependencyService.Get<ISaveRead>();
var s = await ApplicationModel.DependencyService.LoadApplication(userName);
thanks for your Time. 谢谢你的时间。
One doubt you are calling method LoadApplication
from dependency service. 一个疑问是您正在从依赖项服务中调用方法LoadApplication
。
var s = await ApplicationModel.DependencyService.LoadApplication(userName);
and method declaration is LoadApplicationModel
. 方法声明为LoadApplicationModel
。
public async Task<ApplicationModel> LoadApplicationModel(string userName) {
}
maybe that's the problem? 也许那是问题吗? Try using below code for call: 尝试使用以下代码进行通话:
var data = await DependencyService.Get<ISaveRead>()
.LoadApplicationModel(userName);
First you deserialize the file contents and store the ApplicationModel object in m
. 首先,您要反序列化文件内容,并将ApplicationModel对象存储在m
。
using (var file = File.OpenText(userPath)) {
var serializer = new JsonSerializer();
var m = (ApplicationModel) serializer.Deserialize(file, typeof(ApplicationModel));
}
That looks all good but instead of returning m
, you create a new ApplicationModel object and return that. 看起来一切都很好,但是您无需创建m
,而是创建了一个新的ApplicationModel对象并将其返回。
return new ApplicationModel {Username = userName};
I think you should return m
like this (for example): 我认为您应该这样返回m
(例如):
using (var file = File.OpenText(userPath)) {
var serializer = new JsonSerializer();
var m = (ApplicationModel) serializer.Deserialize(file, typeof(ApplicationModel));
m.Username = userName;
return m;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.