目前看1.X的书在学习中,目前市面上还买不到2.0的书籍
我在书上看到这个范例 想实作 但怎么改都有错,找了官方的api也没有说明正确的使用方式,只好再来求助
class HttpController:NSObject {
var delegate:HttpProtocol?
//AJAX读取网页资料类別
func onSearch(urla:String) {
var url:NSURL = NSURL(string: "http://data.taipei.gov.tw/opendata/apply/json/QTdBNEQ5NkQtQkM3MS00QUI2LUJENTctODI0QTM5MkIwMUZE")!
var request:NSURLRequest = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:
{( response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
var httpResponse = response as! NSHTTPURLResponse
if httpResponse.statusCode == 200 {
//以下这行报错,错误讯息为.. Call can throw,bit it is no marked with try and the eooro is not handied
let array: NSArray = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSArray
self.delegate?.didReceiveResults(array)
}
} // Closure 定义结束
)
}
}
请问在2.0下怎样写才是正确的呢?
20151211 现在换这一行出错,错误讯息为
func onSearch(urla:String) {
var url:NSURL = NSURL(string: "http://data.taipei.gov.tw/opendata/apply/json/QTdBNEQ5NkQtQkM3MS00QUI2LUJENTctODI0QTM5MkIwMUZE")!
var request:NSURLRequest = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:
//现在换这一行出错,错误讯息为Invalid conversion from throwing function of type '(NSURLResponse?, NSData?, NSError?) throws -> Void' to non-throwing function type '(NSURLResponse?, NSData?, NSError?) -> Void'
{( response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
var httpResponse = response as! NSHTTPURLResponse
if httpResponse.statusCode == 200 {
let array: NSArray = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSArray
self.delegate?.didReceiveResults(array)
}
} // Closure 定義結束
)
}
}
另各位大大,如果我要查各个物件的使用方式,或是使用时机,或是作什么用的,有没有什么地方可以查 例如 tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
}
ableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? {
像以上这些物件的使用方法 跟 不同 跟 功能 有没有类似 字典这类的东西可以查?
这是swift2的异常.
要么把异常传出去(让onSearch也throw)
要么调用时try或catch, 比如
var array = try NSJSONSerialization.JSONObjectWithData() as? NSArray
别等纸书了, 苹果自己的swift lang guide挺好的.
12/11修改后的那个错误是..我的锅
新错误的原因是这样: 用
try
还是会向上传递异常, 所以代码中那个completionHandler的类型被推断为(NSURLResponse?, NSData?, NSError?) -> Void throws
而不是sendAsynchronousRequest期待的(NSURLResponse?, NSData?, NSError?) -> Void
所以我们不能向上传递异常, 需要在handler内部解决他