- 在項目里新建Podfile文件:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!
target 'ala03' do
pod 'Alamofire', '~> 4.4'
end
執行
pod install
代碼示例
//直接從某個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)