Mihai Blaga
Mihai Blaga

Reputation: 121

Accessing outlets from function

I just started to learn Swift. I created a class that manages an REST API call and the method takes 3 parameters, data, successCallback and failCallback.

All good, I get the data, I parse the JSON, etc.

My problem is that I can't do anything related to IBOutlets inside the successCallback that is passed to the API method. I've tried self.textfield.text, textfield.text, nothing works. No error, nothing.

 func naturalSearch(data : String, callback:(NSDictionary) -> (), fail :(String) -> ()) {

    request(getLink("v2/natural"), data : data, callback : callback, fail : fail)
}

This is the API method.

service.naturalSearch(SearchTextfield.text, callback: processResponse, fail: responseFail)

This is how I call the method. Inside processResponse nothing related to outlets works. I have 3, 2 textfields and a tableview. I've tried hiding/changing label/etc but nothing works.

Thank you, Mihai

Upvotes: 0

Views: 195

Answers (2)

Aseider
Aseider

Reputation: 5925

You can only modify UI Elements in the Main thread. To access it, use:

dispatch_async(dispatch_get_main_queue()) { /* your Code */ }

Upvotes: 0

chustar
chustar

Reputation: 12465

That's because you're working in a callback function, which executes outside the UI thread. You should wrap your UI changing code with dispatch_async.

For example:

dispatch_async(dispatch_get_main_queue(), {
    self.labelOutlet.text = "Text"
})

Upvotes: 1

Related Questions