当用户向下滚动到页面的某个百分比时,我会回发到我的数据库以获取更多数据。但是,当用数据更新子视图时,我注意到滚动中有轻微的冻结。因为所有的调用都是异步的,所以我不确定我做错了什么
func PostBackAsync(PassURL:String, username:String, completion: (jsonData: NSDictionary?, error: NSError?)->Void) {
let post:NSString = "username=\(username)";
let url:NSURL = NSURL(string:PassURL)!
let postData = post.dataUsingEncoding(NSUTF8StringEncoding)!
let postLength = String(postData.length)
//Setting up `request` is similar to using NSURLConnection
let request = NSMutableURLRequest(URL: url)
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")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {urlData, response, reponseError in
if let receivedData = urlData {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300) {
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(receivedData, options: []) as! NSDictionary
//On success, invoke `completion` with passing jsonData.
completion(jsonData: jsonData, error: nil)
} catch {
//On error, invoke `completion` with NSError.
completion(jsonData: nil, error: nil)
} }
else
{
completion(jsonData: nil, error: nil)
}
}
}
task.resume()
}
func PostBack(PassURL:String, username:String) {
PostBackAsync(PassURL, username: username) {jsonData, error in
if let json = jsonData {
dispatch_async(dispatch_get_main_queue(), {
let success:NSInteger = json.valueForKey("success") as! NSInteger
if(success == 1)
{
for var index=0; index < myArray.count; index++
{
//Do some Data Manipulation...
//..............
self.newView.addSubview(a[index] as! String)
self.newView.addSubview(b[index] as! String)
self.myScrollView.contentSize = CGSize(width: aWidth, height: myscrollViewContentSize)
//newView is the main subview inside of the scrollview
self.newView.frame = CGRectMake(0, 0, self.myScrollView.frame.width, myscrollViewContentSize)
}
}
}) }}
在更新此信息时,为什么UIScrollview滚动会稍微冻结,有什么突出的地方?
答案 0 :(得分:0)
您可能需要定义要运行异步操作的线程,以确保它不在UI线程上运行。请参阅此答案:https://stackoverflow.com/a/16283719/2347118