Matt Matt - 3 months ago 8
iOS Question

UIPickerView is slow at updating

I have an app that loads the UIPickerView options from an online JSON file, while it is able to successfully do it, it is extremely slow, and I'm wondering why. The console prints the JSON file in 2 seconds but it likes 12 more seconds to appear in the picker view unless I manually move it. How can I get the PickerView to load the options faster without having to manually move it to show the options?

Here is the part of my code:

import UIKit
class FirstViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var mypickerview: UIPickerView!
var pickerData: [String] = [String]()
override func viewDidLoad() {
super.viewDidLoad()

/*Begin Loading the list*/
let postEndpoint: String = "https://example.com/json.json"
let session = NSURLSession.sharedSession()
let url = NSURL(string: postEndpoint)!
session.dataTaskWithURL(url, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in

guard let realResponse = response as? NSHTTPURLResponse where
realResponse.statusCode == 200 else {
print("Not a 200 response")
return
}
do {
if let ipString = NSString(data:data!, encoding: NSUTF8StringEncoding) {
print(ipString)
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

let One = jsonDictionary["One"] as! String
let Two = jsonDictionary["Two"] as! String
let Three = jsonDictionary["Three"] as! String
let Four = jsonDictionary["Four"] as! String

self.mypickerview.delegate = self
self.mypickerview.dataSource = self
self.pickerData = [One, Two, Three, Four]
self.mypickerview.reloadAllComponents()
self.mypickerview.delegate = self;

}
} catch {
print("bad things happened")
}
}).resume()
/*End Loading the list*/

Answer

you must call ReloadAllcompenents() always on the main queue cause it will update your view . dispatch_async should resolve the problem . hope it help

  let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT

dispatch_async(dispatch_get_global_queue(priority, 0)) {
    dispatch_async(dispatch_get_main_queue()) {
        self.mypickerview.reloadAllComponents()
    }
}