swift3.0 网络编程中 Alamofire 和 SwiftyJSON 的使用

Alamofire 和 SwiftyJSON 是常用的第三方库,前者用于网络编程,后者用于JSON解析

Alamofire 4.0
SwiftyJSON

最新版本的 Alamofire 的 request 方法发生了变化,以前为:

Alamofire.request(.POST, url, parameters).responseJSON()
Alamofire.request(.GET, url).responseJSON()

现在为:

Alamofire.request(url: URLConvertible, method: , parameters: , encoding: , headers:)

用以前的方法都会报错:

Extra argument 'method' in call 或
Extra argument in call

正确用法:Alamofire + SwiftyJSON
ps: POST 踩了很多坑

POST:

        let urlString = "https://www.crs811.com/Json/login.php"
        let params = ["username": self.txtUN.text!,
                      "pwd": self.txtPwd.text!]
        
        Alamofire.request(urlString,
                          method: HTTPMethod.post,
                          parameters: params,
                          encoding: URLEncoding.default,
                          headers: nil).responseJSON { response in
            switch response.result.isSuccess {
            case true:
                if let value = response.result.value {
                    
                    //创建SwiftyJSON对象
                    let json = JSON(value)
                    
                    print(json["success"].string)
                    
                    if let state = json["success"].string {
                        print("=================")
                        print(state)
                        print("=================")
                    }
                }
            case false:
                print(response.result.error)
            }
        }

GET:

  
        let urlString = "https://www.crs811.com/Json/login.php?username=\(self.txtUN.text!)&pwd=\(self.txtPwd.text!)" 
        let url = URL(string: urlString)!

        Alamofire.request(url).validate().responseJSON { response in
            switch response.result.isSuccess {
            case true:
                if let value = response.result.value {
                    
                    //创建SwiftyJSON对象
                    let json = JSON(value)
                    
                    if let state = json["success"].string {
                        print("=================")
                        print(state)
                        print("=================")
                    }
                }
            case false:
                print(response.result.error)
            }
        }

Comments are closed.