php - 我在 Swift 中对 PHP 的 Json 请求出错

标签 php json swift request

这是我向 php 发出 Json 请求并在应用程序中显示数据的代码:

import Foundation

protocol FeedmodelProtocol: class {
    func itemsDownloaded(items: NSArray)
}


class Feedmodel: NSObject, URLSessionDataDelegate {



    weak var delegate: FeedmodelProtocol!



    func downloadItems() {

        let myUrl = URL(string: "http://www.example.net/zumba.php");

        var request = URLRequest(url:myUrl!)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        let postString = "firstName=51&lastName=6";
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in

            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(String(describing: error))")
                return

            }


            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(String(describing: responseString))")
            self.parseJSON(data)
        }
        task.resume()
    }

    func parseJSON(_ data:Data) {

        var jsonResult = NSArray()

        do{
            jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray;
        } catch let error as NSError {
            print(error)

        }

        var jsonElement = NSDictionary()
        let stocks = NSMutableArray()

        for i in 0 ..< jsonResult.count
        {
            print(jsonResult)
            jsonElement = jsonResult[i] as! NSDictionary


            let stock = Stockmodel()

            //the following insures none of the JsonElement values are nil through optional binding
            if  let Datum = jsonElement["Datum"] as? String,
                let Tankstelle = jsonElement["Tankstelle"] as? String,
                let Kraftstoff1 = jsonElement["Kraftstoff1"] as? String,
                let Preis1 = jsonElement["Preis1"] as? String,
                let Kraftstoff2 = jsonElement["Kraftstoff2"] as? String,
                let Preis2 = jsonElement["Preis2"] as? String,
                let Notiz = jsonElement["Notiz"] as? String,
                let longitude = jsonElement["longitude"] as? String,
                let latitude = jsonElement["latitude"] as? String


            {
                print (Datum)
                print(Tankstelle)
                print(Kraftstoff1)
                print(Preis1)
                print(Kraftstoff2)
                print(Preis2)
                print(Notiz)
                print(longitude)
                print(latitude)
                stock.Datum = Datum
                stock.Tankstelle = Tankstelle
                stock.Kraftstoff1 = Kraftstoff1
                stock.Preis1 = Preis1
                stock.Kraftstoff2 = Kraftstoff2
                stock.Preis2 = Preis2
                stock.Notiz = Notiz
                stock.longitude = longitude
                stock.latitude = latitude


            }

            stocks.add(stock)

        }

        DispatchQueue.main.async(execute: { () -> Void in

            self.delegate.itemsDownloaded(items: stocks)

        })
    }
}

我有一个 mySQL PHP,它似乎可以工作,因为我的控制台向我显示:

responseString = Optional("[\"51\",\"6\"]") ( 51, 6 ) Could not cast value of type 'NSTaggedPointerString' (0x1045cbf68) to 'NSDictionary' (0x1045cc288). 2018-06-20 23:29:34.586355+0200 TankBilliger[37631:3753628] Could not cast value of type 'NSTaggedPointerString' (0x1045cbf68) to 'NSDictionary' (0x1045cc288). (lldb)

我不知道是什么问题,有人可以帮忙吗?

谢谢!

最佳答案

问题是,您将数据作为字典获取,但您将其作为字符串

删除这一行再试试

let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(String(describing: responseString))")

此方法 parseJSON() 完成上述功能

关于php - 我在 Swift 中对 PHP 的 Json 请求出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50957354/

相关文章:

javascript - 使用 Javascript 读取 JSON 响应 - 问题

php - 打印模板中的记录

php - 如何将神经网络从 C 语言转换为 PHP

java - 使用 Gson 发布 (Android)

android - 在android中获取json数组键

ios - swift 3 uiview animate 仅显示最后两个动画

swift - 如何从日期对象中提取时区?

swift - 如何快速更改 UIDatePickerView 中的月份名称?

php - 如何在 Python 中获取相同的 PHP adler32 哈希?

php - 传递 $_POST 值以输出各个结果信息