2017-09-09 153 views
-1

我一直在試圖將這段代碼從C#轉換爲Swift 3.0,但沒有語法上的運氣。代碼是直接從https://vpic.nhtsa.dot.gov/api/Home/Index/LanguageExamples,但沒有Swift的例子。將C#JSON POST轉換爲SWIFT 3

感謝您的任何幫助或指針。

string text = "3GNDA13D76S000000;5XYKT3A12CG000000;"; 
string url = @"https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/"; 

var nameValues = new Dictionary<string, string>(); 
nameValues.Add("data", text); 
nameValues.Add("format", "json"); 
HttpClient client = new HttpClient(); 
client.BaseAddress = new Uri(url); 

// using FormUrlEncodedContent 
var name = new FormUrlEncodedContent(nameValues); 
client.DefaultRequestHeaders.Accept.Add(new 
MediaTypeWithQualityHeaderValue("application/json")); 
System.Threading.CancellationToken token = new 
System.Threading.CancellationToken(); 

try { 
    var tmp = client.PostAsync(client.BaseAddress, name, token).Result; 
    var result = tmp.Content.ReadAsStringAsync(); 
} catch (Exception err) { 
    // error handling 
} 
+0

在Swift中查看使用Alamofire進行聯網請求。 – Martheli

+0

看看https://stackoverflow.com/search?q=%5Bswift%5D+%5Balamofire%5D+post – nathan

+0

謝謝你們,我會檢查Alamofire這個以及提供的鏈接。我對Swift仍然很陌生,JSON讓我感到困惑,所以非常感謝。 – user3534305

回答

0

我硬編碼的網址與測試VIN和這對我工作,感謝您的幫助!

let url: String = "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVIN/WBY2Z2C52GV676091?format=JSON" 


    Alamofire.request(url, parameters: nil, encoding: JSONEncoding.default).responseJSON { 
     (response) in 
     print(response.request as Any) // original URL request 
     print(response.response?.allHeaderFields as Any) // URL response 
     print(response.result.value as Any) // result of response serialization 
    }