Reputation: 11672
I am now using Alamofire and SwiftyJSON. I follow this tutorial http://ashishkakkad.com/2015/10/how-to-use-alamofire-and-swiftyjson-with-swift-swift-2-ios-9-xcode-7/
My code:
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet var tblJSON: UITableView!
var arrRes = [[String:AnyObject]]()
override func viewDidLoad() {
super.viewDidLoad()
tblJSON.dataSource = self
// Alamofire.request(.GET, "http://api.androidhive.info/contacts/").response { (request, response, data, error) -> Void in
// print(response)
// let outputString = NSString(data: data!, encoding: NSUTF8StringEncoding)
// print(outputString)
// }
Alamofire.request(.GET, "http://api.androidhive.info/contacts/").responseJSON { (responseData) -> Void in
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()
}
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrRes.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tblJSON.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
var dict = arrRes[indexPath.row]
cell.textLabel?.text = dict["name"] as? String
cell.detailTextLabel?.text = dict["email"] as? String
return cell
}
}
But it crashed at this line:
let swiftyJsonVar = JSON(responseData.result.value!)
my Pod file:
# Uncomment this line to define a global platform for your project
platform :ios, '8.0'
# Uncomment this line if you're using Swift
use_frameworks!
target 'UsingAlamofireAndSwiftyJSON' do
pod 'Alamofire', '~> 3.2.1'
pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git'
end
I use Xcode 7.2, Swift 2.1. Any helps would be appreciated, thanks.
Upvotes: 1
Views: 146
Reputation: 23451
Alamofire and SwiftyJSON understand it very well to avoid the force-unwrapping of the optional you can change the response handler to the JSON response handler like this one:
Alamofire.request(.GET, "http://api.androidhive.info/contacts/").responseJSON { response in
switch(response.result) {
case .Success(let value):
let json = JSON(value)
case .Failure(let error):
print(error.description)
}
}
With the above code you don't need to unwrap the optional, the force-unwrapping it's not recommended as @Eric said in his comment.
I hope this help you.
Upvotes: 2