gpt4 book ai didi

php - 通过 PHP 从 mySQL 获取值到 swift

转载 作者:行者123 更新时间:2023-11-28 12:47:52 25 4
gpt4 key购买 nike

我有一个返回 json_encode 值的 php 文件,当我转到 http 地址时,他们给我值但是我无法从服务器端获取我的应用程序的值(value)我已经尝试了很多次但它没有得到它

func loadData() {

let url = NSURL(string: "http://example.com/getExpo.php")
let request = NSMutableURLRequest(URL: url!)

// modify the request as necessary, if necessary

NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

if error != nil {
// Display an alert message

print(error)

return
}

do {

let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary


if (json != nil) {

//let userId = parseJSON["userId"] as? String

// Display an alert message
let userMessage = json!["id"] as? String

print(userMessage)

} else {

// Display an alert message
let userMessage = "Could not fetch Value"
print(userMessage)

}



} catch {

print(error)

}

}).resume()


}

谁能帮忙,谢谢!!

最佳答案

您的 JSON 响应是字典的数组:

[{"id":"115","expoName":"aziz","expoDetails":"aziz","expoPhone":"aziz","expoLocation":"aziz"}]

但是您正试图将其转换为字典:

let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary

解决方案当然是将其转换为数组:

let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray

如果可以,最好使用 Swift 类型:

let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String:AnyObject]]

然后例如你可以使用一个循环:

if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String:AnyObject]] {
for item in json {
let userMessage = item["id"] as? String
}
}

关于php - 通过 PHP 从 mySQL 获取值到 swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37499653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com