我现在正在使用Alamofire和SwiftyJSON。我按照这个教程http://ashishkakkad.com/2015/10/how-to-use-alamofire-and-swiftyjson-with-swift-swift-2-ios-9-xcode-7/使用Alamofire时出错
我的代码:
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!)
我波德文件:
# 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,雨燕2.1。任何帮助将不胜感激,谢谢。
通过用'responseData.result.value!!'强制展开Alamofire的可选结果,您告诉编译器:*“如果没有值,请崩溃我的应用程序。”*您的应用程序完全按照它告诉的内容... //解决方法是阅读[免费在线Swift文档的这一章:“可选项”。](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics。 html#// apple_ref/doc/uid/TP40014097-CH5-ID330) – Moritz