我是网络开发和 Swift 的新手
我创建了一个基于 ASP.NET 的 Web API,并连接了我的 iOS 应用程序,这样我就可以执行 GET、POST、PUT、DELETE。
当我发送带有特定 ID 号的 GET 请求时 我在 Xcode 中得到如下输出:
Data:
Optional("{\"Id\":1,\"UserName\":\"codeinflash\",\"UserPassword\":\"Wldnrodxxxx\",\"UserEmail\":\"codeinflash@gmail.com\",\"Rebate\":0.00,\"MemCom\":123.44}")
这是 Swift 中的函数:
//GET /api/account/{id}
@IBAction func GetAccount(_ sender: Any) {
let _accountIdNumber = AccountIdNumber.text
if (_accountIdNumber!.isEmpty){
createAlert(title: "Warning", message: "Account ID # is required")
return
}
let restEndPoinst: String = "http://tresmorewebapi2.azurewebsites.net/api/account/" + _accountIdNumber!;
guard let url = URL(string: restEndPoinst) else {
print("Error creating URL")
return
}
var urlRequest = URLRequest(url: url)
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
// api key need urlRequest.setValue(<#T##value: String?##String?#>, forHTTPHeaderField: "APIKey")
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
var userEmail = ""
var rebate = ""
var memcom = ""
let task = session.dataTask(with: urlRequest, completionHandler:
{
(data, response, error) in
print("Error:")
print(error)
print("response:")
print(response)
print("Data:")
print(String(data: data!, encoding: String.Encoding.utf8))
//////////////I think I need logic here to filter the data
userEmail = data.substring of find emailaddress
rebate = data.substring find users' rebate
memcom = same logic
then show alert window with his info and I will show his info on next page which is a Dashboard page view
})
task.resume()
}
老实说,我不确定数据是 JSON 数据,但 Xcode 中的输出是字符串。
我的目的是获取用户的数据并将其存储在局部变量中,这些局部变量将它们传递给 ios Swift 中的下一个 View (仪表板)。
谢谢!
已添加 这是在快速登录功能中从 web api 获取数据的任务
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
var userEmail = ""
var rebate = ""
var memcom = ""
let task = session.dataTask(with: urlRequest, completionHandler:
{
(data: Data?, response: URLResponse?, error: Error?) in
print("Error:")
print(error)
print("response:")
print(response)
print("Data:")
print(String(data: data!, encoding: String.Encoding.utf8))
let json = try? JSONSerialization.jsonObject(with: data!) as! [String: AnyObject] ?? [:];
userEmail = json?["UserEmail"] as? String ?? ""
createAlert(title: "Got User Eamil Address!", message: userEmail)
})
task.resume()
但是我在警报 View 中什么也看不到。我测试过的警报 View 工作正常。
这是我在 Swift 中的 createAlert 函数
func createAlert(title:String, message:String){
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (anction) in
alert.dismiss(animated: true, completion: nil)}))
self.present(alert, animated: true, completion: nil)
}
最佳答案
您已经在评论中找到了答案,但这种方式不那么“敏捷”,对于 Swift 新手来说更具可读性(注意并尝试理解正在发生的事情以及如何使它更紧凑):
do {
guard let unwrappedData = data else{
//data is nil - handle case here
return //exit scope
}
guard let dictionary = try JSONSerialization.jsonObject(with: unwrappedData) as? [String:AnyObject] else {
//you cannot cast this json object to dictionary - handle case here
return //exit scope
}
userEmail = dictionary["UserEmail"]
DispatchQueue.main.async { [weak self] in
self?.createAlert(title: "Got User Eamil Address!", message: userEmail)
}
} catch _ {
//handle error
}
关于ios - 使用 swift 3 从 asp.net web api 中过滤来自 JSON 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43551641/