Alamofire是AFNetworking的swift版本,功能灰常強大。
github:https://github.com/Alamofire/Alamofire
SwiftyJSON是操作json的非常棒的開源庫
github:https://github.com/SwiftyJSON/SwiftyJSON
接下來我做一個簡單的入門小例子,
我使用cocoaPods來管理依賴,需要在Podfile里添加我們需要的兩個庫
source 'https://github.com/CocoaPods/Specs.git' platform :ios, '9.0' use_frameworks! target 'AlamofireDemo' do pod 'Alamofire', '~> 3.4' pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git' end
在terminal里運行
cocoapods會為我們自動生成需要導入的第三方庫的信息。
關閉工程打開cocoaPods為我們生成的工程文件,編輯通過后就能導入這兩個庫了
import Alamofire
import SwiftyJSON
因為我們要訪問網絡,需要在info.plist里開放權限,加入下面的代碼
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
接下來就可以用它Alamofire請求網絡使用swiftyJson解析Json
let currRequest = Alamofire.request(.POST, "http://www.yourweb.com", parameters: ["para1":"aaa", "para2":[0,1,2,3], "para3":NSNull()], encoding: .JSON, headers: ["Content-Type":"application/json"]) currRequest.responseJSON{(responseJson) -> Void in print(responseJson.response?.statusCode) print(responseJson.request) print(responseJson.response) print(responseJson.data) print(responseJson.result) switch responseJson.result { case .Success(let value): print("Value:\(value)") print("------") let swiftyJsonVar = JSON(value) print(swiftyJsonVar) case .Failure(let error): print(error) } }
好了這個簡單的例子就寫完了,還有一個更方便的方法就是用下邊這個庫,他是集成了上邊說的兩個庫,有時間你可以玩一下
https://github.com/SwiftyJSON/Alamofire-SwiftyJSON