json - 使用 swift 4.1 调用 web api(通用处理程序 api)

标签 json swift xcode api

让我先描述 View Controller (页面)。我添加了一个标签和一个按钮。

我尝试在按钮单击操作中使用 swift 4.1. 调用网络 api。但它给出了一个错误。这是错误:

Could not cast value of type '__NSArrayM' (0x1098d8b68) to 'NSDictionary' (0x1098da288).
2018-05-23 10:35:34.217375+0300 apiSor2[1013:63745] Could not cast value of type '__NSArrayM' (0x1098d8b68) to 'NSDictionary' (0x1098da288).
(lldb) 

这是源代码:

import UIKit

class ViewController: UIViewController {


@IBOutlet weak var lblDetail: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func btnClick(_ sender: Any) {

    let url = URL (string: "https://transsupp.com/testApp/ws17.ashx")

    let session = URLSession.shared

    let task = session.dataTask(with: url!)
    {
        (data, response, error) in

        if (error != nil)
        {
            let alert = UIAlertController (title: "error", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)

            let okButton = UIAlertAction(title: "ok", style: UIAlertActionStyle.cancel, handler: nil)

            alert.addAction(okButton)

            self.present(alert, animated:true, completion: nil)
        }
        else
        {
            if (data != nil )
            {
                do
                {
                    let JSONResult = try
                        JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String,AnyObject>
                    DispatchQueue.main.async
                        {
                            print(JSONResult)
                    }
                }
                catch
                {

                }
            }//if (data != nil ) ENDS
        } // if (error != nil) ENDS
    } //let task = session.dataTask(with: url!) ENDS
    task.resume()
} // btnClick ENDS

}

as you see i try to call this api. Please click on it

Api 返回这个

[


{
    "resultCode": "999",
    "resultMessage": "ok",
    "showPopUpPage": "True",
    "contentTextOfPopUpPage": "ws01Settings4Colors.ashx<br/>table:renkAyarlari<br/>showPopUpPage:True<br/><a href=https://www.google.com>click for the link brother</a>and this a skip line in here<br/>it works or not work. lorem ipsum. lorem ipsum. lorem",
    "backgroundColor": "4D5656",
    "textColorOnThePage": "FFFFFF",
    "alertTextColorOnThePage": "E91E63",
    "buttonTextColor": "FFFFFF",
    "buttonBackgroundColor": "81D4FA",
    "alertButtonTextColor": "FFFFFF",
    "alertButtonBackgroundColor": "E91E63",
    "inputTextColor": "4D5656",
    "inputBackgroundColor": "FFFFFF",
    "dropDownMenuTextColor": "4D5656",
    "dropDownMenuBackgroundColor": "FFFFFF",
    "showBackgroundImage": "False",
    "backgroundImagePath": "http://transsupp.com/app/Assets/BackgroundImages/other_background.png"
  }
]

我尝试获取两个 json 返回值:showBackgroundImage 和 backgroundColor 以使用标签显示它们。我怎样才能得到这两个 json 返回?

最佳答案

你的错误解释得很好,你正在将数组转换为字典。

JSON 中的

[] 表示数组或值列表。您正在尝试使用一个。

这一行:

let JSONResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String,AnyObject>

应该是

let JSONResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [[String: Any]]

注意:对于 Swift 4 及更高版本,请勿使用 JSONSerlialization。使用 Codable

注意 2: 不要使用强制解包,即 (data!)。如果它为零,它会使您的应用程序崩溃。使用 if letguard

基本解析

for row in jsonResult {
    if let backgroundColor = row["backgroundColor"] as? String {
         self.color = backgroundColor 
    } 
}

关于json - 使用 swift 4.1 调用 web api(通用处理程序 api),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50482897/

相关文章:

ios - 在 Stripe iOS 实现中调用 Add Token 委托(delegate)后的过程是什么?

ios - 如何在 swift 中启用 restkit 登录

swift - 在 tvOS 中自定义键盘

ios - UIview 使用 pointInside 方法

javascript - 数据表-未捕获的类型错误 : Cannot read property 'length' of undefined

iphone - 解析json数据

javascript - 客户端上的 XML 到 JavaScript 哈希/数组

ios - 如何快速从 UIAlertAction 打开照片库?

ios - 有人发现iOS 14下UIDatePicker损坏了吗?

javascript - 类似于 PHP 中的二维数组