我不知道我的错误在哪里我尝试使用JSON数据解析通过Web服务解析数据
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = NSURL(string: "http://pokeapi.co/api/v2/pokemon/1/")
let request = NSURLRequest(URL: url!)
let config =NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) in
if error==nil {
let post: NSDictionary
if let responsedata = data{
do{
post = try NSJSONSerialization.dataWithJSONObject(responsedata, options: []) as! NSDictionary
}
catch(post){
print ("error inserialization")
}
}
}
})
task.resume()
}
}
答案 0 :(得分:0)
尝试使用以下代码
let url = NSURL(string: "http://pokeapi.co/api/v2/pokemon/1/")
let request = NSURLRequest(URL: url!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if(error == nil)
{
let err : NSError! = nil
do
{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
print(json)
}
catch{
print(err)
}
}
else
{
print(error?.description)
}
}
task.resume()
希望这会对你有所帮助。