在Xamarin里面,IOS、Android、uwp,web服务实现方式都是不一样的,因此同一个web服务 在要3个平台要分别添加3次web服务,关于vs中如何添加web服务,这个就不多说了。
在共享项目中(或者PCL)建立接口。只定义方法,不定义具体。
public interface ISoapService
{
Task <byte[]> DownloadClassById(int id);
Task <byte[]> DownloadClassByName(string name);
Task <int> GetDocumentLenById(int id);
Task <int> GetDocumentLenByName(string name);
Task <int> UploadClass(string name, byte[] bytes);
}
然后在分项目中,继承接口,实现具体方法。(在安卓中实现如下)
class SyncService : ISoapService
{
com.songshizhao.kechengbiao client = new com.songshizhao.kechengbiao();
async public Task<byte[]> DownloadClassById(int id)
{
return client.DownloadClassById(id);
}
async public Task<byte[]> DownloadClassByName(string name)
{
return client.DownloadClassByName(name);
}
async public Task<int> GetDocumentLenById(int id)
{
return client.GetDocumentLenById(id);
}
async public Task<int> GetDocumentLenByName(string name)
{
return client.GetDocumentLenByName(name);
}
async public Task<int> UploadClass(string name, byte[] bytes)
{
return client.uploadclass(name,bytes);
}
}
其中com.songshizhao.kechengbiao是我们引用的WebService,com.songshizhao是自定义的命名空间,这样就在Android平台中实现了引用的web服务,但现在还没“注入”。
在共享项目/PCL的主程序App.cs(名称不一定,但一定继承App)类中添加全局静态变量
public static ISoapService MySoapServiceManager { get; set; }
然后在分平台启动的时候,加载Xamarin.Forms之前对这个 MySoapServiceManager全局静态变量赋值,如在Android平台的MainActivty.cs中初始化中添加:
Schedule.App.MySoapServiceManager =new SyncService();//使用Web服务这样加载Xamarin.Forms前,接口内的方法都已经实现了。调用的时候,直接调用静态属性下面的方法即可,比如:
int r = App.MySoapServiceManager.UploadClass(ScheduleName, App.GetSerializedBytes(MyContentPage.MySchedule)).Result;这样,虽然不同平台实现WebService代码是不同的,但通过注入,在Xamarin.Forms中调用的方法是统一的。Xamarin主要使用了接口和全局静态变量来实现这样的效果。
最后附上windows下的SyncService有什么不同,对比上文Android的。
class SyncService : ISoapService
{
kechengbiaoSoapClient client;
public SyncService()
{
client = new kechengbiaoSoapClient();
}
async public Task<byte[]> DownloadClassById(int id)
{
DownloadClassByIdResponse x = client.DownloadClassByIdAsync(id).Result;
return x.DownloadClassByIdResult;
}
async public Task<byte[]> DownloadClassByName(string name)
{
DownloadClassByNameResponse x = client.DownloadClassByNameAsync(name).Result;
return x.DownloadClassByNameResult;
}
public Task<int> GetDocumentLenById(int id)
{
return GetDocumentLenById(id);
}
public Task<int> GetDocumentLenByName(string name)
{
return GetDocumentLenByName(name);
}
async public Task<int> UploadClass(string name, byte[] bytes)
{
uploadclassResponse x = client.uploadclassAsync(name, bytes).Result;
return x.uploadclassResult;
}
}
·END·