How do I get a return of an ArrayString on a GET call with task.resume ()?

2

Good afternoon, everyone. I'm having trouble loading the contents of a PickerView into my app, because for this it needs to fetch the information on a GET call, the call works and I can set array to the content I need, but I can not do with which the function that builds the array returns it so that I load the PickerView. I build array of categories and, from it, I extract only the "description" information of each category that exists in array , to load in PickerView. Here's the part of my code that I'm having trouble 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 content of array that I need (descriptions), but I need to return it in the function that builds it, that is, I need a return descricoes after task.resume() . I hope you can help me. Thank you in advance.

    
asked by anonymous 29.10.2015 / 20:12

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: I recommend taking a look at the framework Alamofire , it is simple and easy to work the connection part in applications.

    
03.11.2015 / 17:09
0

Thank you, iTSagnar.

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

    
06.11.2015 / 03:13