我试图从http://food2fork.com/about/api
调用Api,但是当我实现这些代码时,它会显示错误。我在这里做的就是这个教程:https://www.topcoder.com/blog/calling-apis-parsing-json-with-swift/
这是我的代码:
import UIKit
import Alamofire
import SwiftyJSON
class ListDishsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var dishsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
print("hello")
let logo = UIImage(named: "bento")
let imageView = UIImageView(image:logo)
self.navigationItem.titleView = imageView
dishsTableView.dataSource = self
dishsTableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func loadDishesData() {
let urlPath = "http://food2fork.com/api/search?key=67fd12776ee242546ac92d3122dabbd9&q=shredded%20chicken"
let url: NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
if error != nil {
print(error!.localizedDescription)
}
var error: NSError?
let jsonResult: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
if error != nil {
// If there is an error parsing JSON, print it to the console
print("JSON Error \(error!.localizedDescription)")
}
})
task.resume()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("DishCell", forIndexPath: indexPath) as! ListDishsTableViewCell
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
}
但是它显示了这样的错误:
任何帮助都会受到赞赏。
答案 0 :(得分:1)
<强>更新强>
在Swift 2中,JSONObjectWithData
没有参数error
。
+ JSONObjectWithData:options:error:
Returns a Foundation object from given JSON data.
Declaration
SWIFT
class func JSONObjectWithData(_ data: NSData,
options opt: NSJSONReadingOptions) throws -> AnyObject
OBJECTIVE-C
+ (id)JSONObjectWithData:(NSData *)data
options:(NSJSONReadingOptions)opt
error:(NSError * _Nullable *)error