Swift:Alamofire使用Cocoapod安裝與疑難雜症
環境:Swift 3 , Alamofire 4.4

性喜孤獨,優雅的無以復加。 — — 《刺蝟的優雅》
Alamofire 讓開發者優雅地處理 Swift 中的網路操作,之前愚鈍如我,竟然異想天開、硬著頭皮寫了幾十幾百行 code 就為了 HTTP Request,好家在之前前往 Swift Girls 做了小小 Firebase 的演講,因緣際會認識了 David Lin 大大,深入的請教理解下,開啟了我的另一片天。好的沒錯,之前的腦包硬幹全部 打 掉 重 練!沒想到,在 pod Alamofire 時就碰到了好大一包的的問題啊囧… 這篇主要分享 pod 跟初步 compile 過程中所碰到的疑難雜症,回想過程中可能有偏誤還請大家多指教。
一、前言
首先,大家在谷歌 Alamofire 時,都會看到以下這篇文:
但這是 Swift 2 的版本,大多程式碼已經不適用了,這是我第一次碰到轉換大魔王,不過還是得說這篇文整體邏輯還是敘述得挺好。另外推薦一篇文:Updating Alamofire Calls to Swift 3.0,幫助 Swift 2 to 3 的你。
二、淺談怎麼 pod
如果你沒有安裝過 cocoapods,請於終端機輸入:
gem install cocoapods
- 成立 Xcode 專案:這邊應該很簡單就不多說了
- 指定到資料夾,在這裡我放在桌面並取名為 alamofireDemo:
cd Desktop/alamorfireDemo
3. 新增 Podfile:
pod init4. 點開 Podfile,會看到一個小視窗
5. 添加圖中兩行程式碼,並儲存(Command+S),可前往 Alamofire 看原始解釋:
# Uncomment the next line to define a global platform for your project
# platform :ios, ’10.0’target 'alamofireDemo' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!# Pods for alamofireDemo
pod 'Alamofire', '~> 4.4'end
6. Install 剛剛的Podfile
pod install按下 return 之後,問題發生了,而且接二連三!
三、疑難雜症
Error 1: [!] Unable to satisfy the following requirements
[!] Unable to satisfy the following requirements:
- `Alamofire (~> 4.4)` required by `Podfile`
None of your spec sources contain a spec satisfying the dependency: `Alamofire (~> 4.4)`.
You have either:
* out-of-date source repos which you can update with `pod repo update`.
* mistyped the name or version.
* not added the source repo that hosts the Podspec to your Podfile.
Note: as of CocoaPods 1.0, `pod repo update` does not happen on `pod install` by default.參考了千千萬萬種方法,嘗試了各式各樣的結果,刪掉幾十次 Podfile 再重裝、再刪、再裝,但坦白說因為做了太多事情,我不是很確定最後是怎麼成功的,這邊提供幾個解決方式(以下非一步一步的順序唷,每個方式都是獨立的):
(1) pod repo update:直觀的從上面的 Note: as of CocoaPods 1.0, `pod repo update` does not happen on `pod install` by default.,嘗試在終端機中做這個動作,但因為太沒耐心,所以做到一半就關掉視窗,那看到其他人的回饋是有部分人成功除錯,有些人沒成功,所以請耐心地給他一點時間。
(2) 關掉 Xcode、關機、重開:我是蠻懷疑是不是真的,這個情況下對我而言是沒用處,就是「電腦出現奇怪顏色的螢幕?強制關機重新開機試試」的概念,但如果這麼一塊蛋糕也不妨試試。
(3)sudo gem install cocoapods --pre& pod setup:更新 CocoaPods ,--pre到即將發行的版本,sudo gem update --system(如果 gem 的版本太舊),推薦看這文 CocoaPods: Getting Started,另外提醒,pod setup耗時非常久,我從十點安裝到凌晨一點,等到頭髮白,所以可以去泡茶聊天打麻將再回來。
先從疑難雜症抽離一下,接續「淺談怎麼 pod」,成功除錯以上問題後:

7. pod install 成功了:新增三個檔案、成功安裝 Alamofire 、未來使用 xcworkspace 開發。
〈貼心提醒:開啟 xcworkspace 的第一件事情,Build 專案(Command+B)〉
原本滿心歡喜,終於要柳暗花明又一村了嗎!!! BUT…
Error 2: 除了 AlamofireVersionNumber , xcworkspace 無法找到其他的 Alamofire,如下圖。

這邊有兩個方法,都可以試試看:
(1) Xcode 關掉、關機、重開:沒錯!又是「電腦螢幕出現奇怪的顏色,敲一敲打一打強制關機重開試試」,我自己實際嘗試這個方法有幾次有用,Xcode可以自動找到 Alamofire,但不知為什麼會默默又不行了。
(2) Keep typing:實際把 Alamofire 打出來,並繼續做動作,比方說 .request ,就會看到如下圖,Alamofire還是存在的,只是選字上的 bug。

四、結語
疑~原來只有兩個蟲蟲,卻搞了一整天,再次享受到Coding的美好,就是無限的DEBUG啊(無奈燦笑ing… 之後會再追加 Alamofire 的後續實作,希望這篇文對你有幫助囉!
