ios - 如何使用控制台输出来使用 if 条件?

标签 ios swift dictionary

如何使用控制台输出来使用 if 条件?

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()

console output

如何使用此输出 {"status":"No"} 我想使用 if 条件使用状态值。

示例:

if status == "YES"
{
   print("Entered")
}
else
{
   print("Not Entered")
}

最佳答案

尝试将字符串转换为字典格式。

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数据,因此您可以直接将数据转换为数据,而不是转换为String [字符串:字符串]

if let respJSON = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String : String]
{
    if respJSON["status"] == "No"
    {
       print("No")
    }
    else
    {
       print("yes")
    }
}

关于ios - 如何使用控制台输出来使用 if 条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48785633/

相关文章:

ios - swift 中 textview 字符串的 tapgesture

ios - 设置 max lines 为 3 并根据标签内容调整高度

ios - Swift:作为参数传递的字典始终为空

ios - Node.js 发布到 Heroku 时请求超时

c# - .Net 线程安全中的静态字典

c++ - 从 map 返回迭代器的函数

iOS : No Notification Received from Facebook App Request

c# - ios webview - 如何在应用程序未运行时检查通知

iphone - iOS 上每个线程可以有多个运行循环吗?

java - 从 map 中获取最高 n 个数字的最简洁方法?