Juanma Juanma - 6 months ago 13
Swift Question

Check for a String in an array

How can I know if there's a specific string in an array? I want to do something like this:

if (getUsuarios().containsString(usuarioView.text!) == false) {

print("hola")

alerta("Ups, vas a tener que cambiar algo", texto2: "Ese usuario ya existe", alertaNum: "refreshAlert6")

usuarioView.text = ""


}


getUsuarios
is this:

func getUsuarios() -> String {
var usuariosDataBase = [String]()

Alamofire.request(.GET, url)
.responseJSON { response in
print(response)


do {
let json = try NSJSONSerialization.JSONObjectWithData(response.data!, options: .AllowFragments)

if let blogs = json as? [[String: AnyObject]] {
for blog in blogs {
if let usuario = blog["usuario"] as? String {
usuariosDataBase.append(usuario)
}
}
}
} catch {
print("error serializing JSON: \(error)")
}

print(usuariosDataBase)


}

return "\(usuariosDataBase)"
}

Answer

Alamofire.request works asynchronously.

A function / method which includes an asynchronous call can never have a return value.

You need a callback for example

func getUsuarios(completion : ([String]) -> Void) {
  var usuariosDataBase = [String]()

  Alamofire.request(.GET, url)
    .responseJSON { response in
      print(response)

      do {
        let json = try NSJSONSerialization.JSONObjectWithData(response.data!, options: .AllowFragments)

        if let blogs = json as? [[String: AnyObject]] {
          for blog in blogs {
            if let usuario = blog["usuario"] as? String {
              usuariosDataBase.append(usuario)
            }
          }
        }
      } catch {
        print("error serializing JSON: \(error)")
      }
     completion(usuariosDataBase)
  }
}

and call it with

getUsuarios() { (usarios) in
  if usarios.filter({$0.containsString(self.usuarioView.text!)}).isEmpty == false {

    print("hola")

    self.alerta("Ups, vas a tener que cambiar algo", texto2: "Ese usuario ya existe", alertaNum: "refreshAlert6")

    self.usuarioView.text = ""

  }
}

Important note: The code is very simple. You should add proper error handling, at least considering the error parameter returned by Alamofire.

Comments