如果使用控制台输出条件,如何使用?
let myURL = URL(string: "http://www.digi.com/laravel_api_demo/api/demoapipost")
let request = NSMutableURLRequest(url: myURL!)
request.httpMethod = "POST"
let postString = "username=rahul"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
guard let _: Data = data, let _:URLResponse = response, error == nil else {
print("error")
return
}
if let dataString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
{
print(dataString)
}
}
task.resume()
如何使用此输出{“status”:“No”} 我想使用if条件使用状态值。
示例:
if status == "YES"
{
print("Entered")
}
else
{
print("Not Entered")
}
答案 0 :(得分:0)
尝试将String转换为Dictionary格式。
func convertToDictionary(from text: String) -> [String: String]? {
guard let data = text.data(using: .utf8) else { return nil }
let anyResult = try? JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String]
}
let string1 = "{\"status\":\"No\"}"
let dictionary1 : [String : String] = convertToDictionary(from: string1)!
if dictionary1["status"] == "No"
{
print("No")
}
else
{
print("yes")
}
根据@moritz建议,您拥有JSON Data
,因此您可以直接将String
转换为data
[String : String]
。
if let respJSON = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String : String]
{
if respJSON["status"] == "No"
{
print("No")
}
else
{
print("yes")
}
}