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

时间:2018-05-23 07:58:07

标签: json swift xcode api

首先让我描述视图控制器(页面)。我添加了一个标签和一个按钮。

我尝试在按钮点击操作中使用swift 4.1.调用web 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回报?

2 个答案:

答案 0 :(得分:0)

您的错误很好地解释了,您正在将数组转换为字典。

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 
    } 
}

答案 1 :(得分:0)

错误显示您的结果是一个数组,但您将其转换为字典。根据你给的api。它返回一个数组,它的第一个元素是你想要的字典。