I'm studying Swift Animation. Its material is written in Swift 2, so I had to convert its original code into Swift 3. I have learned from it along, but now I have a big problem. Xcode successfully built this code but produced a runtime error message. (I attached the image file.)
I can't solve this at all on my own as I guess I have little experience. How can I fix this? Help.
func setQuote() {
//fadeOut
//getting data from API
let dataService = DataService()
dataService.getQuoteData {(quote, author) -> Void in
UIView.animate(withDuration: 0.5, animations: {
//fadeIn and backgroundColor
//quote
self.quoteLabel.text = quote
//author - optional binding
//if no author
}, completion:nil)
}
}
class DataService {
func getQuoteData(_ completion: @escaping (_ quote: String, _ author: String?) -> ()) {
let url = URL(string: "http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json")!
URLSession.shared.dataTask(with: url, completionHandler: { ( data: Data?, response: URLResponse?, error: NSError?) -> Void in
do {
let jsonDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let aQuote = jsonDictionary["quoteText"] as! String
let aAuthor = jsonDictionary["quoteAuthor"] as! String
DispatchQueue.main.async(execute: { () -> Void in
completion(aQuote, aAuthor)
})
} catch {
print("invalid json query")
}
} as! (Data?, URLResponse?, Error?) -> Void).resume()
}
}
You can try rewrite it like this
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
do {
let jsonDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let aQuote = jsonDictionary["quoteText"] as! String
let aAuthor = jsonDictionary["quoteAuthor"] as! String
DispatchQueue.main.async(execute: { () -> Void in
completion(aQuote, aAuthor)
})
} catch {
print("invalid json query")
}
}
task.resume()
or simply change the ( data: Data?, response: URLResponse?, error: NSError?) -> Void
to ( data, response, error) -> Void
and remove the as! ...
as! ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.