How to use Alamofire and SwiftyJSON with Swift?
Alamofire is an HTTP networking library written in Swift.
SwiftyJSON makes it easy to deal with JSON data in Swift.
Steps to setup the CocoaPods
- Open Terminal
- CocoaPods runs on ruby so update your system.
sudo gem update --system
-
Install CocoaPods
Install CocoaPods by using following command :
sudo gem install cocoapods
If you are facing issue in EL Capitan or macOS Sierra then use following command :
sudo gem install -n /usr/local/bin cocoapods
- Setup the Pod
pod setup
Note : This process will take some time.
Steps to add Alamofire and SwiftyJSON Pods to your project
- Open Terminal
- Navigate to the directory containing your AlamofireSwiftyJSONSample project by using the cd command:
cd ~/Path/To/Folder/Containing/AlamofireSwiftyJSONSample
- Give the init command
pod init
It will create Podfile in your project's directory.
- Open the Podfile using command
open -a Xcode Podfile
- Edit the pod file with your pods which you want to use and must remember the targets. Add pods to the particular target where you want to use that pod.
In Swift you have to add one more line use_frameworks!
So, Your Podfile will look like as :
platform :ios, '9.0'
use_frameworks!
target 'AlamofireSwiftyJSONSample' do
pod 'Alamofire'
pod 'SwiftyJSON'
end
target 'AlamofireSwiftyJSONSampleTests' do
end
target 'AlamofireSwiftyJSONSampleUITests' do
end
- Go to terminal and give following command
pod install
Note : From now you have to use the .xcworkspace of your project.
Let's use it in our project
Import it in your file where you want to use it.
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController {
}
Here is simple get request URL : http://api.androidhive.info/contacts/ we will use it to get data from it via Alamofire.
Alamofire.request("http://api.androidhive.info/contacts/").responseData { (resData) -> Void in
print(resData.result.value!)
let strOutput = String(data : resData.result.value!, encoding : String.Encoding.utf8)
print(strOutput)
}
Here we have used conversion of data to the String.
We can do batter and go easy with the SwiftyJSON.
Alamofire.request("http://api.androidhive.info/contacts/").responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
print(swiftyJsonVar)
}
}
Let's Populate a table with the JSON response
Declaration of variables and outlets:
@IBOutlet var tblJSON: UITableView!
var arrRes = [[String:AnyObject]]() //Array of dictionary
Fetch data from Request and reload the table:
Using Alamofire Version 2.0.2:
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(.GET, "http://api.androidhive.info/contacts/").responseJSON { (req, res, json) -> Void in
let swiftyJsonVar = JSON(json.value!)
if let resData = swiftyJsonVar["contacts"].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.tblJSON.reloadData()
}
}
}
Using Alamofire Version 3.3.1 :
Due to Alamofire Version 3 and syntax change old code not work.
You can check Alamofire 3.0 Migration Guide.
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(.GET, "http://api.androidhive.info/contacts/").responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["contacts"].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.tblJSON.reloadData()
}
}
}
}
Using Alamofire Version 4.0 :
Due to Alamofire Version 4 and syntax change old code not work.
You can check Alamofire 4.0 Migration Guide.
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request("http://api.androidhive.info/contacts/").responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["contacts"].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.tblJSON.reloadData()
}
}
}
}
Delegate methods of table :
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("jsonCell")!
var dict = arrRes[indexPath.row]
cell.textLabel?.text = dict["name"] as? String
cell.detailTextLabel?.text = dict["email"] as? String
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrRes.count
}
Conclusion
This is a Sample of Alamofire with SwiftyJSON on Github.
Check other articles/tutorials for iOS.
Thank you all the watchers
Happy Coding
Keep Learning, Following, Swifting
plzz tell me the code POST data also
Hi, I followed your procedure but did not get the expected result. I tested adapting to my scenario and I get the following message:
atal error: Unexpectedly found nil while implicitly unwrapping an Optional value
2019-09-04 21:01:28.228350-0300 Sivirino.com[3363:1890501] Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
Thanks Buddy ๐น