我正在尝试从我的 API 获取信息并在 APP 上显示它,一切都很好,除了 View 上的打印速度很慢。在我从我的 API 获得 JSON 信息后,它停留了 ±5-8 秒。
有我的异步发布功能:
class func postAsync(post :NSString, def: Bool = true, completionHandler: ((AnyObject?, NSError?) -> Void)) {
var post_url : NSString
/* SOME CODE */
post_url = post
let jsonData = NSDictionary();
var postData:NSData = post_url.dataUsingEncoding(NSASCIIStringEncoding)!
var postLength:NSString = String( postData.length )
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = nil
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler: { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if (error != nil) {
completionHandler(nil, error)
println("API error: \(error), \(error.userInfo)")
}
var jsonError:NSError?
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers, error: &jsonError) as NSDictionary
if (jsonError != nil) {
println("Error parsing json: \(jsonError)")
completionHandler(nil, jsonError)
}
else {
... error ...
completionHandler(jsonData, nil)
}
})
}
我是这样调用它的:
WebReq.postAsync("default", def: true) { (data, error) -> Void in
if let er = error {
println("\(er)")
}
if let arr = data?["arr"] as? NSArray {
for (index,album) in enumerate(arr) {
var position = CGRect(x: 0, y: index*21, width: 90, height: 20)
var label = UILabel(frame: position)
label.textAlignment = NSTextAlignment.Center
label.text = album["text"] as? NSString
self.view.addSubview(label)
}
}
}
结果会在 5-8 秒后打印出来。如果我进行了同步,那么我的整个应用程序会挂起更短的时间,比如 2-5 秒
如果在我尝试创建 UILabel 的那个地方执行 println(),那么它会在我获取并解析我的信息后立即出现。
有什么建议吗?不知道哪里出了问题
请您参考如下方法:
您已指示 sendAsynchronousRequest 为完成 block 使用后台操作队列(您实例化了一个新的 NSOperationQueue())。因此,您正在尝试从后台线程进行 UI 更新。但是 UI 更新必须发生在主线程上。
要么
在
sendAsynchronousRequest调用中指定主队列:NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { response, data, error in ... )或
手动将 UI 更新分派(dispatch)回主队列
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { response, data, error in // do stuff in background queue // when ready to update model/UI dispatch that to main queue dispatch_async(dispatch_get_main_queue()) { ... } )或
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { response, data, error in // do stuff in background queue // when ready to update model/UI dispatch that to main queue NSOperationQueue.mainQueue().addOperationWithBlock { ... } )
