首页 > 解决方案 > Swift 4.2 - Alamofire 突然不工作了

问题描述

我将 Alamofire 4.7 与 Swift 4.2 一起使用,自从将我的代码转换为 Swift 4.2 之后,Alamofire 就完全不起作用了。

我有一个简单的电话,如下所示:

func createUser(username: String, email: String, password: String, passwordConfirm: String, completion: @escaping (_ result: String) -> Void)
    {

        let parameters: Parameters = [
            "username" : username,
            "email" : email,
            "password" : password,
            "confirm_password" : passwordConfirm
        ]

        Alamofire.request(webservice + "?action=register", method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.httpBody, headers: [:]).responseJSON { response in

            if(response.error == nil)
            {

                if let result = response.result.value {

                    let jsonData = result as! NSDictionary

                    if(jsonData["response"] == nil)
                    {
                        completion("")
                    }
                    else
                    {
                        completion(jsonData["response"] as! String)
                    }

                }
            }
            else
            {
                completion((response.error?.localizedDescription)!)
            }

        }
    }

在检查了我的 api 之后,所有参数都得到了正确填充,它调用了正确的方法 (?action=register) 但我的帖子是空的。我究竟做错了什么?

标签: iosswiftalamofire

解决方案


您知道使用 Swift 4.2 可以超级轻松地解析 JSON 吗?我最近将它与拨号代码表视图一起使用 - 数据是本地 JSON 文件:

    struct Countries: Codable {
    let countries: [Country]
}

struct Country: Codable {
    let code: Int
    let name: String
    let flagImage: String
}

enum CodingKeys: String, CodingKey {
    case code
    case name
    case flagImage
}

class CountryListVC: UITableViewController {

    func loadJSON() {

        if let path = Bundle.main.path(forResource: "countryDiallingCodes", ofType: "json") {

            do {
                let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
                let jsonObj = try JSONDecoder().decode(Countries.self, from: data)
                print("JSON Object: ", jsonObj)
                countries = jsonObj.countries

            } catch let error {
                print (error)
            }
        } else {
            print ("Error in path")
        }
    }

推荐阅读