如何使用swift5在tableview中显示Alamofire响应

时间:2019-10-10 06:11:24

标签: ios swift xcode swift5 alamofire-request

 class ViewController: UIViewController{


   override func viewDidLoad() {
    super.viewDidLoad()
     let parameters: [String: Any] = ["userid": "1","start":"0"]
       let url = "https://sample.php"
    self.request = AF.request(url, method: .post, parameters:parameters)
    if let request = request as? DataRequest {
        request.responseString { response in
            do{
                let dictionary = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
               print(dictionary)



            }catch{ print("something wrong")

            }
        }
    }
}

var request: Alamofire.Request? {
    didSet {
        //oldValue?.cancel()
    }
}
 }`

以上格式用于Alamofire发布请求方法的响应数据。我有来自服务器的响应数据,但如何在表视图中显示响应数据却隐藏了json字符串

1 个答案:

答案 0 :(得分:0)

您必须为存储数据创建一个模型类。例如,

class User: NSObject {

        var ID:Int?
        var FirstName:String?
        var LastName:String?
        var Password:String?
        var Email:String?
        var Gender:String?
        var PhoneNumber:String?

    override init() {}

    init(dic:[String: Any]) {
        self.ID = dic["ID"] as? Int
        self.FirstName = dic["FirstName"] as? String
        self.LastName = dic["LastName"] as? String
        self.Password = dic["Password"] as? String
        self.Email = dic["Email"] as? String
        self.Gender = dic["Gender"] as? String
        self.PhoneNumber = dic["PhoneNumber"] as? String
    }
}

使用Alamofire的请求,

Alamofire.request(url, method: .post, parameters: parameters).responseJSON { (response) in
            if response.result.isSuccess == true {
                if let JSON = response.result.value {
                    if let dictionary = JSON as? [String: Any] {
                        let isSuccess = dictionary["success"] as! Bool
                        if isSuccess == true {
                            if let userDic = dictionary["result"] {
                                let currentUser = User.init(dic: userDic as! [String : Any])
                            }
                        }
                    }
                }
            }
}

现在,您可以访问任何字段的值,例如。 "FirstName"如下

let fName = currentUser.FirstName

不要忘记,所有密钥名称都与接收的JSON密钥相同。