无法从完成块中返回变量:

时间:2016-06-17 18:19:14

标签: ios swift asynchronous closures

我使用以下函数通过RESTEngine.sharedEngine.registerUser函数从我的服务器获取一些数据。 " userCreationCall"进行API调用,解析它返回的JSON,创建用户,然后在完成块中传递该用户。

" makeUser"然后通过将其中的用户传递给另一个函数来处理该完成块,该函数返回用户对象以供我在我的应用程序中的其他位置使用。

func userCreationCall(first: String, last: String, email: String, completionHandler: (User?, ErrorType?) -> ()) {
RESTEngine.sharedEngine.registerUser(email, firstName: first, lastName: last, age: 12, success: { response in
    if let response = response, result = response["resource"], id = result[0]["_id"] {            
        let params: JSON =
        ["name": "\(first) \(last)",
            "id": id as! String,
            "email": email,
            "rating": 0.0,
            "nuMatches": 0,
            "nuItemsSold": 0,
            "nuItemsBought": 0]
        let user = User(json: params)
        completionHandler(user, nil)
    }
    }, failure: { error in
        completionHandler(nil, error)
    })
}

func makeUser(first: String, last: String, email: String) {

    userCreationCall(first, last: last, email: email) { user, error in
        guard error == nil else {
            print("Error creating a user! : \(error)")
            return
        }

        returnUser(user!)
    }
}

func returnUser(user: User) -> User {
    return user
}

出于测试目的,我在viewDidLoad中进行以下调用,打算使用" testUser"分配在" makeUser":

的完成块内传递的用户对象
override func viewDidLoad() {
    super.viewDidLoad()  
    let testUser = makeUser("John", last: "Doe", email: "johnDoe@gmail.com")
    print("\(testUser)")
}

然而,当我打印testUser时,它仍然是空白的(这意味着永远不会在" makeUser"'完成块)中分配用户对象。有没有人知道我的逻辑/实现出错了?提前致谢!

1 个答案:

答案 0 :(得分:0)

您还需要makeUser中的完成块,例如

func makeUser(first: String, last: String, email: String, completion:((User?) -> Void)) {

  userCreationCall(first, last: last, email: email) { user, error in
    guard error == nil else {
        print("Error creating a user! : \(error)")
        completion(nil)
        return
    }

    completion(user)
  }
}

override func viewDidLoad() {
    super.viewDidLoad()  
    makeUser("John", last: "Doe", email: "johnDoe@gmail.com") { user in 
       if user != nil {
          print("\(user!)")
       }
    }
}

但实际上并不需要额外的功能

override func viewDidLoad() {
    super.viewDidLoad()

    userCreationCall("John", last: "Doe", email: "johnDoe@gmail.com") { user, error in
      if error != nil {
         print("Error creating a user! : \(error!)")
      } else {
         print("\(user!)")
         // do something with the new created user
      }
   }
}