How to get a return of an Array<String> in a GET call with task.resume()?

Asked

Viewed 125 times

2

Good afternoon, you guys. I’m having a hard time uploading the content of a Pickerview in my app, as it needs to fetch the information in a call GET, the call works and I can assemble the array with the content I need, but I can’t get the function that builds the array return it for me to click on Pickerview. I build a array of categories and, from it, extract only the information "description" of each category that exists in the array, to click on Pickerview. Below is the part of my code I’m having problems with:

var categoriaArray = Array<Categoria>()

for obj:AnyObject in post {
    let dict = obj as! NSDictionary
    let categoria = Categoria()

    categoria.descricao = dict["descricao"] as! String
    categoria.id = dict["id"] as! Int
    categoria.valorCasadinha = dict["valorCasadinha"] as! Double
    categoria.valorTerceira = dict["valorTerceira"] as! Double

    categoriaArray.append(categoria)
}

var descricoes = Array<String>()

for categoria in categoriaArray{
    descricoes.append(categoria.descricao)
}

print("Descrições: \(descricoes)")
print("Quantidade de Categorias: \(categoriaArray.count)")

})
task.resume()

I can print the contents of array that need (descriptions), but need to be returned in the function that builds it, ie, need a return descricoes after the task.resume(). I hope you can help me. Thanks in advance.

  • Do you have a way to add more code? In general if your array has the values you expect then, technically, all you would need to do is give reload in Picker and make it take the new array values.

2 answers

2


One way to do this is by passing a callback to your function:

class func getDescricoes(completionHandler: (result: Array<String>) -> ()) {
    ...
    let task = session.dataTaskWithURL(url) {
        data, response, error in
        ...
        for categoria in categoriaArray{
            descricoes.append(categoria.descricao)
        }

        completionHandler(result: descricoes)
    }
    ...
    task.resume()
}

to call this method:

override func viewDidLoad() {
    Ingressos.getDescricoes {
        result in
        println("Descrições: \(result)")     
    }
}

ps.: recommend taking a look at the framework Alembic, it is simple and easy to work the connecting part on applications.

0

Thank you, iTSagnar.

I did it this way and it worked. With the Alamofire I tried too, but with me it was not very simple :/ But I got my return. Thanks :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.