【发布时间】:2018-07-27 14:32:08
【问题描述】:
我用 C#(Xamarin) 编写了一个从 API 获取令牌的休息服务。我在 Swift 中需要相同的代码,我试图到处寻找,但找不到任何可靠的东西。看看下面的代码
public class RestService
{
HttpClient client;
public RestService()
{
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded "));
}
public async Task<Token> Login(User user)
{
string webUrl = Utility.AppConstant.ApiUrl + "/token";
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("grant_type", "password"));
postData.Add(new KeyValuePair<string, string>("username", user.Username));
postData.Add(new KeyValuePair<string, string>("password", user.Password));
var content = new FormUrlEncodedContent(postData);
var response = await PostResponseLogin<Token>(webUrl, content);
return response;
}
public async Task<T> PostResponseLogin<T>(string webUrl, FormUrlEncodedContent content) where T : class
{
try
{
var response = await client.PostAsync(webUrl, content);
var jsonResult = response.Content.ReadAsStringAsync().Result;
var responseObject = JsonConvert.DeserializeObject<T>(jsonResult);
return responseObject;
}
catch
{ return null; }
}
【问题讨论】:
-
有什么特别的事情你不知道该怎么做吗?我们不会为你写的
-
这里恐怕不是代码外包
-
这样的 Swift 例子不胜枚举。不过,您可能不会在这里找人将您的代码重写为 Swift。