swift 网络请求框架 Alamofire

使用cocoapods安装网络请求库 Alamofire

pod 'Alamofire'

默认是get请求

 Alamofire.request("https://api.500px.com/v1/photos").responseJSON { (DataResponse) in
            print("请求的数据 == \(DataResponse.data!)")
            if let Json = DataResponse.result.value{
                print("Json:\(Json) ")
                // NSData->NSDictonary
                let dic = try? JSONSerialization.jsonObject(with: DataResponse.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: Any]
                let status = dic? ["statuss"]
                print("status is \(status ?? String("测试默认值"))")
            }
        }

get 请求

let parameters: Dictionary = ["key" : "93c921ea8b0348af8e8e7a6a273c41bd"]
        Alamofire.request("http://apis.haoservice.com/weather/city", method:.get, parameters:parameters).responseJSON { (response) in
            switch response.result {
            case .success:
                print("SUCCESS")
            case .failure:
                print("ERROR")
            }
        }

post 请求

let parameters: Dictionary = ["key" : "93c921ea8b0348af8e8e7a6a273c41bd"]
let headers: HTTPHeaders = ["Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
                                    "Accept": "application/json"]
        Alamofire.request("http://apis.haoservice.com/weather/city", method: .post,  parameters:parameters) .responseJSON {response  in
            print("result==\(response.result)")
//有错误就打印错误,没有就解析数据
            if let Error = response.result.error
            {
                print(Error)
            }
            else if let jsonValue = response.result.value
            {
                print("code = \(jsonValue)")
            }            

        }

你可能感兴趣的:(swift 网络请求框架 Alamofire)