Alamofire學(xué)習(xí)小結(jié)(基本使用)

一 安裝:

cocoapods的配置文件如下:(cocoapods需要更新版本疮茄,才支撐swift的第三方框架纯衍,更新的方法可以參考:CocoaPods1.1.1更新

Podfile:? ? ? ??

?source 'https://github.com/CocoaPods/Specs.git'? ? ? ??

?platform :ios, '10.0'? ? ? ??

?use_frameworks!? ? ? ? ? ? ? ??

?target '' do

pod 'Alamofire', '~> 4.0'

end

完成之后添加一下動(dòng)態(tài)庫(kù)儒旬,如下圖:


?二 基礎(chǔ)用法:

Response handler

Alamofire 的網(wǎng)絡(luò)操作都是異步進(jìn)行(用response handler)的,最基本的請(qǐng)求代碼如下:

Alamofire.request("https://httpbin.org/get").responseJSON { response in

print(response.request)? // original URL request

print(response.response) // HTTP URL response

print(response.data)? ? // server data

print(response.result)? // result of response serialization

if let JSON = response.result.value {

print("JSON: \(JSON)")

}}

Alamofire 默認(rèn)包含物種類型的response handlers:response responseString responseJSON responseData

兩種高級(jí)的方式:

1.Chained Response Handlers(鏈?zhǔn)骄纠⒁猓簳?huì)訪問服務(wù)器數(shù)據(jù)多次)

Alamofire.request("https://httpbin.org/get")

.responseString { response in

print("Response String: \(response.result.value)")

}

.responseJSON { response in

print("Response JSON: \(response.result.value)")

}

It is important to note that using multiple response handlers on the same Request requires the server data to be serialized multiple times. Once for each response handler.

2.Response Handler Queue(多線程)

Response handlers 默認(rèn)是在主線程上運(yùn)行的疏唾,可以添加到GCD隊(duì)列中。

let utilityQueue = DispatchQueue.global(qos: .utility)

Alamofire.request("https://httpbin.org/get").responseJSON(queue: utilityQueue) { response in

print("Executing response handler on utility queue")

}

判斷服務(wù)器返回的數(shù)據(jù)有效性的方式:

Manual Validation

Alamofire.request("https://httpbin.org/get")

.validate(statusCode: 200..<300)

.validate(contentType: ["application/json"])

.responseData { response in

switch response.result {

case .success:

print("Validation Successful")

case .failure(let error):

print(error)

}}

Automatic Validation

Automatically validates status code within 200...299 range, and that the Content-Type header of the response matches the Accept header of the request, if one is provided.

Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in

switch response.result {

case .success:

print("Validation Successful")

case .failure(let error):

print(error)

}}

?三 HTTP相關(guān):

?HTTP Methods

public enum HTTPMethod: String {

case options = "OPTIONS"

case get? ? = "GET"

case head? ? = "HEAD"

case post? ? = "POST"

case put? ? = "PUT"

case patch? = "PATCH"

case delete? = "DELETE"

case trace? = "TRACE"

case connect = "CONNECT"

}

默認(rèn)方法是 get

Alamofire.request("https://httpbin.org/post", method: .post)

Alamofire.request("https://httpbin.org/put", method: .put)

Alamofire.request("https://httpbin.org/delete", method: .delete)

Parameter Encoding(參數(shù)編碼)

Alamofire 支持3種類型的參數(shù)編碼:URL, JSON and PropertyList摊滔。也可以自定義類型阴绢,需支持ParameterEncoding協(xié)議。

?HTTP Headers(Http 頭部)

let headers: HTTPHeaders = [

"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",

"Accept": "application/json"

]

Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in

debugPrint(response)

}

Alamofire SessionManager提供了默認(rèn)的頭部艰躺,內(nèi)容如下:

? Accept-Encoding, which defaults to gzip;q=1.0, compress;q=0.5, per RFC 7230 §4.2.3.

? Accept-Language, which defaults to up to the top 6 preferred languages on the system, formatted like en;q=1.0, per RFC 7231 §5.3.5.

? User-Agent, which contains versioning information about the current app. For example: iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0, per RFC 7231 §5.5.3.

如果需要自定義頭部信息呻袭,需要這么來做:

If you need to customize these headers, a custom URLSessionConfiguration should be created, the defaultHTTPHeaders property updated and the configuration applied to a new SessionManager instance.

?Authentication(驗(yàn)證)

支持四種驗(yàn)證機(jī)制:

HTTP Basic? ? ? ? ? HTTP Digest? ? ? ? Kerberos? ? ? NTLM

基本的用法:

let user = "user"

let password = "password"

Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)")

.authenticate(user: user, password: password)

.responseJSON { response in

debugPrint(response)

}

?四 Downloading Data to a File(下載文件)

Alamofire可以加載數(shù)據(jù)到內(nèi)存緩存或者沙盒緩存,Alamofire.request用來將數(shù)據(jù)保存在內(nèi)存中腺兴,這比較高效棒妨,但不適用于大文件的保存;使用Alamofire.download可以將大文件保存到應(yīng)用的沙盒中。

Alamofire.download("https://httpbin.org/image/png").responseData { response in

if let data = response.result.value {

let image = UIImage(data: data)

}}

如果需要后臺(tái)下載券腔,需這樣設(shè)置:

let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.app.background")

let sessionManager = Alamofire.SessionManager(configuration: configuration)

sessionManager.download("https://httpbin.org/image/png").responseData { response in

if let data = response.result.value {

let image = UIImage(data: data)

}}

使用DownloadFileDestination

可以將文件從臨時(shí)路徑移動(dòng)到目標(biāo)路徑:

let destination: DownloadRequest.DownloadFileDestination = { _, _ in

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

let fileURL = documentsURL.appendPathComponent("pig.png")

return (fileURL, [.removePreviousFile, .createIntermediateDirectories])

}

Alamofire.download(urlString, to: destination).response { response in

print(response)

if response.error == nil, let imagePath = response.destinationURL?.path {

let image = UIImage(contentsOfFile: imagePath)

}}

也可以使用建議的路徑:

let destination = DownloadRequest.suggestedDownloadDestination(directory: .documentDirectory)

Alamofire.download("https://httpbin.org/image/png", to: destination)

監(jiān)測(cè)下載進(jìn)度:

Alamofire.download("https://httpbin.org/image/png")

.downloadProgress { progress in

print("Download Progress: \(progress.fractionCompleted)")

}

.responseData { response in

if let data = response.result.value {

let image = UIImage(data: data)

}}

可以將下載的進(jìn)程加入到一個(gè)GCD隊(duì)列中:

let utilityQueue = DispatchQueue.global(qos: .utility)

Alamofire.download("https://httpbin.org/image/png")

.downloadProgress(queue: utilityQueue) { progress in

print("Download Progress: \(progress.fractionCompleted)")

}

.responseData { response in

if let data = response.result.value {

let image = UIImage(data: data)

}}

?五 其他部分:

?Statistical Metrics(統(tǒng)計(jì))

統(tǒng)計(jì)網(wǎng)絡(luò)延時(shí),響應(yīng)時(shí)間等數(shù)據(jù)

Alamofire.request("https://httpbin.org/get").responseJSON { response in

print(response.timeline)

}

cURL Command Output (調(diào)試工具)

CustomStringConvertible

let request = Alamofire.request("https://httpbin.org/ip")

print(request)

// GET https://httpbin.org/ip (200)

CustomDebugStringConvertible

let request = Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"])

debugPrint(request)


參考代碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末拘泞,一起剝皮案震驚了整個(gè)濱河市纷纫,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌陪腌,老刑警劉巖辱魁,帶你破解...
    沈念sama閱讀 216,402評(píng)論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異诗鸭,居然都是意外死亡染簇,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門强岸,熙熙樓的掌柜王于貴愁眉苦臉地迎上來锻弓,“玉大人,你說我怎么就攤上這事蝌箍∏嘧疲” “怎么了?”我有些...
    開封第一講書人閱讀 162,483評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵妓盲,是天一觀的道長(zhǎng)杂拨。 經(jīng)常有香客問我,道長(zhǎng)悯衬,這世上最難降的妖魔是什么弹沽? 我笑而不...
    開封第一講書人閱讀 58,165評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮筋粗,結(jié)果婚禮上策橘,老公的妹妹穿的比我還像新娘。我一直安慰自己亏狰,他們只是感情好役纹,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,176評(píng)論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著暇唾,像睡著了一般促脉。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上策州,一...
    開封第一講書人閱讀 51,146評(píng)論 1 297
  • 那天瘸味,我揣著相機(jī)與錄音,去河邊找鬼够挂。 笑死旁仿,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播枯冈,決...
    沈念sama閱讀 40,032評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼毅贮,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了尘奏?” 一聲冷哼從身側(cè)響起滩褥,我...
    開封第一講書人閱讀 38,896評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎炫加,沒想到半個(gè)月后瑰煎,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,311評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡俗孝,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,536評(píng)論 2 332
  • 正文 我和宋清朗相戀三年酒甸,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片赋铝。...
    茶點(diǎn)故事閱讀 39,696評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡插勤,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出柬甥,到底是詐尸還是另有隱情饮六,我是刑警寧澤,帶...
    沈念sama閱讀 35,413評(píng)論 5 343
  • 正文 年R本政府宣布苛蒲,位于F島的核電站卤橄,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏臂外。R本人自食惡果不足惜窟扑,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,008評(píng)論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望漏健。 院中可真熱鬧嚎货,春花似錦、人聲如沸蔫浆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)瓦盛。三九已至洗显,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間原环,已是汗流浹背挠唆。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留嘱吗,地道東北人玄组。 一個(gè)月前我還...
    沈念sama閱讀 47,698評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親俄讹。 傳聞我的和親對(duì)象是個(gè)殘疾皇子哆致,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,592評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容