我将项目从swift 1升级到2,并且我试图解决所有已经出现的问题。
我仍然有一些离开,我正在努力绕开。
我有这种方法,正如你所看到的那样抛出错误。我知道它与do / try / catch有关,但是我无法让他们离开我的任何尝试。
struct EventDao {
// MARK: Functions
/**
Get all the upcoming events
*/
static func getUpcoming(callback: (NSArray?, String?) -> Void) {
let request = NSMutableURLRequest(URL: NSURL(string: Constants.makeUrl("/events"))!)
request.HTTPMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let token = NSUserDefaults.standardUserDefaults().stringForKey("myezteamToken")
request.addValue("Bearer \(token!)", forHTTPHeaderField: "Authorization")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { <-- // INVALID CONVERSION FROM THROWING FUNCTION OF TYPE '(_, _, _) THROWS -> VOID' TO NON-THROWING FUNCITON '(NSDATA?, NSURLRESPONSE?, NSERROR?) -> VOID'
(data, response, error) -> Void in
if error != nil {
callback(nil, error.localizedDescription) <-- // TYPE OF EXPRESSION IS AMBIGUOUS WITHOUT MORE CONTEXT
} else {
let newData: NSData = data
let upcomingEvents: NSArray = try NSJSONSerialization.JSONObjectWithData(newData, options: NSJSONReadingOptions.AllowFragments) as! NSArray
callback(upcomingEvents, nil)
}
}
task.resume()
}
}
答案 0 :(得分:1)
首先,您需要打开error
属性,如果它不是零。然后,您需要将您的JSON序列化代码包装在do / try / catch中。你得到的错误信息是红鲱鱼。一旦你在do / try / catch中包装JSON东西,它就会消失。当您将as?
的结果转换为JSONObjectWithData
时,您还需要使用NSArray
。试试这个:
static func getUpcoming(callback: (NSArray?, String?) -> Void) {
let request = NSMutableURLRequest(URL: NSURL(string: "bob")!)
request.HTTPMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let token = NSUserDefaults.standardUserDefaults().stringForKey("myezteamToken")
request.addValue("Bearer \(token!)", forHTTPHeaderField: "Authorization")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil {
callback(nil, error!.localizedDescription)
}
else {
let newData: NSData = data!
let upcomingEvents: NSArray?
do {
upcomingEvents = try NSJSONSerialization.JSONObjectWithData(newData,
options: NSJSONReadingOptions.AllowFragments) as? NSArray
} catch {
upcomingEvents = nil
}
callback(upcomingEvents, nil)
}
}
task.resume()
}