Reputation: 1251
I have that class linked to register of new users on my system.
class ProfileNewAddressViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
// MARK: Properties
@IBOutlet weak var streetTextField: UITextField!
@IBOutlet weak var streetComplementTextField: UITextField!
@IBOutlet weak var zipCodeTextField: UITextField!
@IBOutlet weak var stateTextField: UITextField!
@IBOutlet weak var countryTextField: UITextField!
@IBAction func saveNewAddressPressed(sender: UIButton) {
}
var countries:[String] = []
let countriesPicker = UIPickerView()
func populateCountries() {
countries = RestApiManager.sharedInstance.getCountries()!
countriesPicker.reloadAllComponents()
}
override func viewDidLoad() {
super.viewDidLoad()
populateCountries()
countriesPicker.delegate = self
countriesPicker.dataSource = self
countryTextField.inputView = countriesPicker
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return countries.count
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
return countryTextField.text = countries[row]
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return countries[row]
}
In this code I call function getCountries listed bellow:
func getCountries() -> [String]? {
var countries:[String] = []
makeHTTPGetRequest(baseURL + "countries", parameters: ["page_size": "0"], completionHandler: { (data, response, error) in
let data = data
do {
let jsonResult:NSArray = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as! NSArray
for var i = 0; i < jsonResult.count; ++i {
var countriesDict = jsonResult.objectAtIndex(i) as! NSDictionary
countries.append(countriesDict["title"] as! String)
}
}
catch {
print("Error: \(error)")
}
})
return countries
}
That calls a HTTP GET:
private func makeHTTPGetRequest(path: String, parameters: [String: AnyObject], completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionTask {
let parameterString = parameters.stringFromHttpParameters()
let requestURL = NSURL(string:"\(path)?\(parameterString)")!
let request = NSMutableURLRequest(URL: requestURL)
request.HTTPMethod = "GET"
//request.setValue("Bearer " + userInfoDefaults.stringForKey("accessToken")!, forHTTPHeaderField: "Authorization")
request.setValue("Bearer diU8PIBuGHHlvD5PKstRDRbHdCEMxpb5", forHTTPHeaderField: "Authorization")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler:completionHandler)
task.resume()
return task
}
For some reason, my pickerView is not displaying any values on the screen. I already debugged the code and noticed that countries array is being filled with the correct values. I need to reload some component in any way to it works?
Upvotes: 3
Views: 347
Reputation: 66
It looks like you are populating countries in the background during your completetion handler. That code will not populate countries array until it is done making the network call, but you reload the picker immediately. I would suggest calling the lickers reloadAllComponents inside the getCountries function once the array is populated, but it looks like that call is in another object, so maybe add a callback(completetion handler) to the getCountries function that it calls once the array is populated. You will have to call the picker's reloadAllComponents from the main thread.
func populateCountries() {
countries = RestApiManager.sharedInstance.getCountries!({
dispatch_async(dispatch_get_main_queue()){
countriesPicker.reloadAllComponents()
})
}
}
Then getCountries can be this
func getCountries(handler:()->Void) -> [String]? {
var countries:[String] = []
makeHTTPGetRequest(baseURL + "countries", parameters: ["page_size": "0"], completionHandler: { (data, response, error) in
let data = data
do {
let jsonResult:NSArray = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as! NSArray
for var i = 0; i < jsonResult.count; ++i {
var countriesDict = jsonResult.objectAtIndex(i) as! NSDictionary
countries.append(countriesDict["title"] as! String)
}
}
catch {
print("Error: \(error)")
}
handler()
})
return countries
}
Upvotes: 4
Reputation: 948
I am not sure if this might work, but you can try add an property observer for countries with:
var countries: [String] = [] {
didSet{
countriesPicker.realodAllComponents()
}
}
Upvotes: 1