NSUrlSession在Swift中运行缓慢 [英] NSUrlSession Running Slow in Swift
问题描述
我正在迅速将数据下载到我的iOS应用中.尽管最终发生的事情是加载,但即使我处于快速连接状态,它最多也可能需要20秒钟才能加载,因此它的工作正常.我不明白为什么会这样.我几乎要考虑在应用打开之前下载所有数据,尽管我不想这么做,因为我知道可以加快速度,因为YouTube和Facebook之类的应用可以在不超过20分钟的时间内加载和刷新. 20秒哎呀,YouTube在不到那么短的时间内加载视频.我知道我的服务器不如以前快,但是我确实知道我的服务器比那快.我确实想提醒您,页面加载的速度确实很快.请帮忙.这是NSUrlSession代码.
In swift I am downloading data in swift to my iOS app. It works just fine although what ends up happening is it can take up to 20 seconds for it to load even though I am on a fast connection. I don't understand why this happens. I was almost thinking about downloading all the data before the app opens although I don't want to do that because I know it is possible to speed it up which I know is possible because apps like YouTube and Facebook can load and refresh in less than 20 seconds. Heck, YouTube loads videos in less then that amount of time. I know my server isn't as fast as there's but I do happen to know my server is faster then that. I do want to remind you that the page does end up loading just not quickly. Please help. Here is the NSUrlSession code.
func contactApiUrl(){
let url = "http://www.example.com"
let nsUrl = NSURL(string:url)
let nsUrlRequest = NSURLRequest(URL: nsUrl!)
let task = NSURLSession.sharedSession().dataTaskWithRequest(nsUrlRequest){
(data, response, error) in
if let dat = data{
let contents = NSString(data:dat, encoding:NSUTF8StringEncoding) as! String
self.aboutText.text = contents
}
}
task.resume()
}
我要感谢任何可以提前帮助我的人.
I want to thank anybody who can help me with this in advance.
推荐答案
func contactApiUrl(){
guard
let nsUrl = NSURL(string: "http://www.example.com")
else { return }
NSURLSession.sharedSession().dataTaskWithRequest(NSURLRequest(URL: nsUrl)){
(data, response, error) in
guard
let data = data,
let contents = String(data: data, encoding: NSUTF8StringEncoding)
else { return }
// All UI updates should be done at the main queue.
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.aboutText.text = contents
})
}.resume()
}
这篇关于NSUrlSession在Swift中运行缓慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!