【发布时间】:2016-07-21 22:54:46
【问题描述】:
我只想使 JSON 响应与提到的类异步。 我特别想使用我在 NSOperation 类中的方法。这对我来说似乎很复杂,因为我不知道我的方法“parseResponse”的参数应该来自哪里。这是我的尝试+相关代码。
感谢任何形式的帮助。
编辑了代码和 cmets 以解决问题。 我知道我的旧代码已经是异步的,但我想重写它,所以新的解决方案是使用 NSOperationQueue 和 NSBlockOperation。
func jsonParser() {
let urlPath = "https://api.github.com/users/\(githubName)/repos"
guard let endpoint = NSURL(string: urlPath) else {
print("Error creating endpoint")
let alert = UIAlertController(title: "Error Github Name Request", message: "Error creating endpoint", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
self.navigationController?.popToRootViewControllerAnimated(true)
}
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil);
return
}
// How would I implement this part of the code, to make the response asynchronous?
let queue = NSOperationQueue()
let o = JSONParser()
var blockOperation = NSBlockOperation { () -> Void in
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
o.parseResponse(data, response: response, error: error, completionHandler: (parsedData: [ViewControllerTableView.Repository], error: NSError) -> () )
}.resume()
}
queue.addOperation(blockOperation)
// The commented code below is my old solution. And I want to take my old
//solution and rewrite it so it actually uses NSOperationQueue and
// NSBlockOperation
/*
let request = NSMutableURLRequest(URL:endpoint)
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
do {
guard let data = data else {
let alert = UIAlertController(title: "Error Github Name Request", message: "\(JSONError.NoData)", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
self.navigationController?.popToRootViewControllerAnimated(true)
}
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil);
throw JSONError.NoData
}
guard let json = try NSJSONSerialization.JSONObjectWithData(data, options:.AllowFragments) as? [[String: AnyObject]] else {
let alert = UIAlertController(title: "Error Github Name Request", message: "\(JSONError.ConversionFailed)", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
self.navigationController?.popToRootViewControllerAnimated(true)
}
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil);
throw JSONError.ConversionFailed
}
self.owner=json[0]["owner"]!["login"]! as! String
self.allRepos.removeAll()
for a in json {
let temp:Repository = Repository(id: (a["id"] as? Int)!,name: (a["name"] as? String), size: (a["size"] as? Int)!, watchers: (a["watchers"] as? Int), created_at: (a["created_at"] as? String)!, descr: (a["description"] as? String)!)
self.allRepos.append(temp)
}
self.tableRefresh(self.allRepos)
} catch let error as JSONError {
print(error.rawValue)
} catch let error as NSError {
print(error.debugDescription)
}
}.resume()
*/
}
class JSONParser {
func parseResponse(data: NSData?, response:
NSURLResponse?,error:
NSError?,completionHandler: (parsedData:
[Repository],error: NSError) -> ())
{
}
}
【问题讨论】:
-
@Rob 我想异步解析响应。你是对的,这已经发生了,但我现在想用 NSOperationQueue 和 NSBlockOperation 来实现。
-
@Rob 是的,但我真的很想重写我的代码并尝试使用 NSOperationQueue 和 NSBlockOperation。只是为了良好的做法。
-
不相关,
dataTaskWithRequest在后台队列上运行其完成处理程序,因此如果您进行任何 UI 更新或想要同步模型更新,您需要将它们分派到主队列。
标签: json swift asynchronous nsurlsession httpwebresponse