Swift網路請求庫Alamofire
阿新 • • 發佈:2018-11-05
Alamofire由cnoon大神編寫的基於swift的網路請求庫
Github下載地址
[TOC]
執行限制:
- iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+
- Xcode 7.3+
CocoaPods安裝:
1.下載CocoaPods
$ gem install cocoapods
CocoaPods 0.39.0+ is required to build Alamofire 3.0.0+.
2.修改Podfile檔案:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!
pod 'Alamofire', '~> 3.3'
3.下載:
$ pod install
使用Alamofire
發出請求
import Alamofire
Alamofire.request(.GET, url)
響應處理
Alamofire.request(.GET, url, parameters: ["key": "value"])
.responseJSON { response in
print(response .request)
print(response.response)
print(response.data)
print(response.result)
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
響應JSON處理
Alamofire.request(.GET, url)
.responseJSON { response in
debugPrint(response)
}
HTTP方法
public enum Method: String {
case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
}
上傳檔案
let fileURL = NSBundle.mainBundle().URLForResource("Default", withExtension: "png")
Alamofire.upload(.POST, url, file: fileURL)
上傳進度
Alamofire.upload(.POST, url, file: fileURL)
.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
print(totalBytesWritten)
// This closure is NOT called on the main queue for performance
// reasons. To update your ui, dispatch to the main queue.
dispatch_async(dispatch_get_main_queue()) {
print("Total bytes written on main queue: \(totalBytesWritten)")
}
}
.responseJSON { response in
debugPrint(response)
}
下載
Alamofire.download(.GET, url) { temporaryURL, response in
let fileManager = NSFileManager.defaultManager()
let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let pathComponent = response.suggestedFilename
return directoryURL.URLByAppendingPathComponent(pathComponent!)
}
HTTP頭部
Alamofire.request(.GET, url, headers: ["key":"value"])
.responseJSON { response in
debugPrint(response)
}