gpt4 book ai didi

ios - NSURLSession dataTaskWithURL 非常 "slow"

转载 作者:行者123 更新时间:2023-11-28 21:30:02 37 4
gpt4 key购买 nike

我的意思是“慢”,回调类型等待远程服务器超时以有效触发(调用 vimeo 提要,解析它,然后在场景中显示 uiviews)

我大多不明白它是如何工作的。我希望在返回响应后立即从回调中填充我的 View

有下面的代码(rubymotion,但你可能明白了):

session = NSURLSession.sharedSession
url = NSURL.URLWithString(ALBUMS_URL)
downloadTask = session.dataTaskWithURL( url, completionHandler: lambda { |data, response, error|
# 'puts' prints the result in the console, you get it as soon as the response arrives
puts data
# testing with a simple view
v = UIView.alloc.initWithFrame(CGRectMake(0,0,@width/2,200))
v.backgroundColor = UIColor.blackColor
self.view.addSubview v # ==> takes forever to effectively appear on the scene
})

我最终在主线程中设置了以下内容

NSURLSession.sessionWithConfiguration(
NSURLSessionConfiguration.defaultSessionConfiguration,
delegate:nil,
delegateQueue: NSOperationQueue.mainQueue
)

应该使用其他东西来完成此类任务?有没有办法“强制”更新 View ?

最佳答案

您的 UI 更新时间过长的原因不是操作时间过长,而是因为 NSURLSessionDataTask 在后台线程 中完成。您可能知道,您不应该从后台线程更改 UI,只能从主线程更改。

您将整个 URL session 的回调放在主队列中的解决方案“解决”了这个问题,但不是正确的方法,因为您现在是在主队列中进行网络操作,对于可能发生的事情应该尽可能少在后台完成(如网络操作)。

要解决此问题,您需要在后台线程中执行网络操作,然后最后在主线程中调用 UI 更改逻辑。你可以做一个简单的 dispatch_async() 调用来创建一个更新 UI 的 block ,就像这样(抱歉,我不熟悉 RubyMotion,所以我用 Objective-C 写这个):

// in the callback for NSURLSessionDataTask:
NSLog(@"%@", data);

// Dispatch the UI-related logic as a block on the main-thread
dispatch_async(dispatch_get_main_queue(), ^{
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,width/2,200)];
v.backgroundColor = [UIColor blackColor];
[self.view addSubview:v];
});

关于ios - NSURLSession dataTaskWithURL 非常 "slow",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36499740/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com