-5

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)"
}
Hamish
  • 78,605
  • 19
  • 187
  • 280
Juanma
  • 3
  • 1
  • 1
    possible duplicate http://stackoverflow.com/questions/24028860/how-to-find-index-of-list-item-in-swift – LHIOUI May 09 '16 at 16:48
  • 2
    This question is incredibly unclear. Please [edit it](http://stackoverflow.com/posts/37121167/edit) and include a clear problem statement. – Hamish May 09 '16 at 16:50
  • 2
    The code doesn't work anyway because `Alamofire.request` works asynchronously and `getUsuarios()` will never return the actual received data. – vadian May 09 '16 at 16:53

1 Answers1

0

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.

vadian
  • 274,689
  • 30
  • 353
  • 361