-1
我该如何将此代码转换为Swift?Objective C到Swift JSON解析
- (void)fetchFeed
{
NSString *requestString = @"https://bookapi.bignerdranch.com/private/courses.json";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *dataTask =
[self.session dataTaskWithRequest:req
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
self.courses = jsonObject[@"courses"];
NSLog(@"%@", self.courses);
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}];
[dataTask resume];
}
我尝试将其转换在此,但Xcode的崩溃
func fetchFeed(){
var requestString = "http://bookapi.bignerdranch.com/courses.json"
var url = NSURL(string: requestString)
var req = NSURLRequest(URL: url!)
var dataTask:NSURLSessionDataTask = self._session.dataTaskWithRequest(req, completionHandler: { (data : NSData!, response : NSURLResponse!, error : NSError!) -> Void in
//var json:NSDictionary = NSJSONSerialization.JSONObjectWithData(data: NSData!, options: NSJSONReadingOptions.allZeros, error: NSError!)
var json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: NSErrorPointer.null()) as NSDictionary
self._courses = json["courses"]![0] as NSArray
println("\(json)")
})
dataTask.resume()
}
问题应该是这一行self._courses = json["courses"]![0] as NSArray
我想那一定是某种与自选的错误。不知道什么
我该如何解决它?请帮我
还要确保它是一个数组而不是字典。 – 2014-11-22 20:02:59