我现在正在使用 Alamofire 和 SwiftyJSON。我遵循本教程 http://ashishkakkad.com/2015/10/how-to-use-alamofire-and-swiftyjson-with-swift-swift-2-ios-9-xcode-7/
我的代码:
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
}
}
但它在这一行崩溃了:
let swiftyJsonVar = JSON(responseData.result.value!)
我的 Pod 文件:
# 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
我使用 Xcode 7.2、Swift 2.1。任何帮助将不胜感激,谢谢。
最佳答案
Alamofire 和 SwiftyJSON 对此非常了解,为了避免可选的强制解包,您可以将响应处理程序更改为 JSON 响应处理程序,如下所示:
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)
}
}
使用上面的代码,您不需要解包可选的,正如@Eric 在他的评论中所说,不推荐强制解包。
希望对你有帮助
关于swift - 使用 Alamofire 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36250519/