在swift3.0使用Alamofire

  1. 在项目里新建Podfile文件:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!

target 'ala03' do
    pod 'Alamofire', '~> 4.4'
end
  1. 执行pod install

  2. 代码示例

//直接从某个url获取数据
        
        let testurl = "http://www.xxx.html"
        

        Alamofire.request(testurl).responseJSON { response in
            print("Request: \(String(describing: response.request))")   // original url request
            print("Response: \(String(describing: response.response))") // http url response
            print("Result: \(response.result)")                         // response serialization result
            
            if let json = response.result.value {
                print("JSON: \(json)") // serialized json response
                print("json数据")

            }
            
            if   let data = response.data,  let utf8Text = String(data: data, encoding: .utf8) {
               print("Data: \(utf8Text)") // original server data as UTF8 string
                print("data数据")
             
                }
            }
        }
//从douban api取数据
let URLStringGetBooks = "https://api.douban.com/v2/book/search"
        
Alamofire.request(URLStringGetBooks,method: .post, parameters: ["tag":"Swift","count":1], encoding: JSONEncoding.default, headers: [:]).responseJSON { (resp) -> Void in
            if let error = resp.result.error {
                print(error)
            } else if let value = resp.result.value {
                print(value)
            }

        }
//下载网络图片,存放到本地目录
let url1 = "https://httpbin.org/image/png"
let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
Alamofire.download(url1, to: destination)

你可能感兴趣的:(在swift3.0使用Alamofire)