douji1999 2018-06-20 21:33
浏览 67

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

this is my code for the Json request to php and to show the data in the app:

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)

        })
    }
}

I have a mySQL PHP what seems to work because my Console shows me that:

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)

I don't know what the problem is, can anyone help?

Thank You!

  • 写回答

1条回答 默认 最新

  • douben6670 2018-06-29 12:42
    关注

    The problem is , your getting data as dictionary but you taken as string

    delete this line and try

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

    This method parseJSON() do above functionality

    评论

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)