如何通过 JSON 将数组从 php 解压到 Swift

Posted

技术标签:

【中文标题】如何通过 JSON 将数组从 php 解压到 Swift【英文标题】:How to unpack an array from php into Swift via JSON 【发布时间】:2016-10-22 08:16:22 【问题描述】:

我正在从 php 中将 Array 检索到 Swift 中,其中包含来自几个 SQL 查询的值。

在 Swift 中通过以下代码发送、接收和打印数组:

let task = URLSession.shared.dataTask(with: request)  (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async


let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]

print (json)

该数组包含 userDetailsCommunities,它在 Xcode 中的输出(通过打印调试)如下所示:

Optional(["userDetails": 
id = 2;
"user_email" = "radowns82@gmail.com";
"user_name" = "<null>";
, "communities": <__NSArrayI 0x60000002f500>(

name = Gallelio;
,

name = GallelioPart2;

)
])
Optional(["userDetails": 
id = 30;
"user_email" = "sam.bawdry@gmail.com";
"user_name" = "Samuel Bawdry";
, "communities": <__NSArrayI 0x60800026e180>(

name = TesetTester;
,

name = West***2;
,

name = WinnersOnly;
,

name = OneTwoThree;
,

name = WhoopdeWhoop;

)
])

我现在如何解压缩“社区”的内容,以便可以在 UITableVIew 中显示其内容 - 我已经设置了 UITableView 并使用了“虚拟数据”。

这是完整的 Swift 脚本:

import UIKit

protocol UsernameSentDelegate 
func userLoggedIn(data: String)


class LoginViewController: UIViewController 

var delegate: UsernameSentDelegate? = nil

@IBOutlet weak var userEmailTextField: UITextField!
@IBOutlet weak var userPasswordTextField: UITextField!
@IBOutlet weak var displayUserName: UILabel!
var communitiesArray  = [String]()


@IBAction func loginButtonTapped(_ sender: AnyObject)


    let userEmail = userEmailTextField.text;
    let userPassword = userPasswordTextField.text;

    if (userPassword!.isEmpty || userEmail!.isEmpty)  return; 

// send user data to server side


    let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/userLogin.php");

    var request = URLRequest(url:myUrl!);

    request.httpMethod = "POST";

    let postString = "email=\(userEmail!)&password=\(userPassword!)";

    request.httpBody = postString.data(using: String.Encoding.utf8);

    let task = URLSession.shared.dataTask(with: request)  (data: Data?, response: URLResponse?, error: Error?) in
        DispatchQueue.main.async
            


               if(error != nil)
                

                    //Display an alert message
                    let myAlert = UIAlertController(title: "Alert", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert);
                    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
                    myAlert.addAction(okAction);
                    self.present(myAlert, animated: true, completion: nil)
                    return
                

                do 

                    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]

                    if let arr = json?["communities"] as? [String:String] 
                    self.communitiesArray = arr.map  $0["name"] 
                


                    // retrieve login details and check to see if all ok

                    if let parseJSON = json 

                        let returnValue = parseJSON["status"] as? String

                        if(returnValue != "error")
                        

                            self.delegate?.userLoggedIn(data: userEmail! )

                            UserDefaults.set(UserDefaults.standard)(true, forKey: "isUserLoggedIn");


                            self.dismiss(animated: true, completion: nil)


                         else 
                            // display an alert message
                            let userMessage = parseJSON["message"] as? String
                            let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
                            let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
                            myAlert.addAction(okAction);
                            self.present(myAlert, animated: true, completion: nil)
                        

                    
                 catch
                
                    print(error)
                


        



    

    task.resume()




override func prepare(for segue: UIStoryboardSegue, sender: Any?)


    if segue.identifier == "loginView" 
        let createViewController: ViewController = segue.destination as! ViewController
        createViewController.communities = communitiesBox
        print (communitiesBox)
    







【问题讨论】:

if let communities = json["communities"] as Array&lt;Dictionary&lt;String, Any&gt;&gt; //you have communities as Array and load it using table view methods... raywenderlich.com/120442/swift-json-tutorial 我觉得对你有帮助 【参考方案1】:

您可以使用两种方法来做到这一点。

声明一个[[String:String]] 类型的Array 并将其与您的TableView 一起使用。

var communitiesArray = [[String:String]]()

let task = URLSession.shared.dataTask(with: request)  (data: Data?, response: URLResponse?, error: Error?) in

    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
    if let arr = json["communities"] as? [[String:String]] 
        self.communitiesArray = arr
          
    DispatchQueue.main.async 
        self.tableView.reloadData()
    

现在在tableView 方法集中使用communitiesArraycell.label.text = self.communitiesArray[indexPath.row]["name"]

如果您的communities 仅获得name 值,那么如果您只创建[String] 类型的数组,就像这样。

var communitiesArray = [String]()

let task = URLSession.shared.dataTask(with: request)  (data: Data?, response: URLResponse?, error: Error?) in

    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
    if let arr = json["communities"] as? [[String:String]] 
        self.communitiesArray = arr.flatMap  $0["name"]
          
    DispatchQueue.main.async 
        self.tableView.reloadData()
    

现在在tableView 方法集中使用communitiesArray 就像cell.label.text = self.communitiesArray[indexPath.row] 一样

【讨论】:

我收到错误,“类型'(键:字符串,值:字符串)'没有下标成员。在 self.communitiesArray = arr.map 行上...它也迫使我把a ? in 'json?["communities"] - 对吗? 太棒了! xCode 想要添加一些 (? 在 json 之后,! 在 ["name"] 之后,但它看起来运行良好!干杯

以上是关于如何通过 JSON 将数组从 php 解压到 Swift的主要内容,如果未能解决你的问题,请参考以下文章

php如何将json数据写入数据库

如何在 IOS 上使用 Swift 解析 JSON,从 PHP 服务脚本发送?

通过 POST 将 JSON 编码的变量从 PHP 传递到 Javascript

我如何通过 json 将数据从我的设备发送到我的 php 文件

PHP 如何从 AJAX 调用中发布多个数组/json 值并在同一个 SQL 查询中运行它们?

PHP-AJAX:如何通过 php/json 数组从查询中填充 jquery 数据表