问题
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.
回答1:
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()
}
来源:https://stackoverflow.com/questions/33290436/nsurlsession-running-slow-in-swift