2017-01-02 47 views
0

之前,這是我的代碼:等待此完成處理程序完成執行的函數返回的價值

 func authenticateCredentials(usernameString: String, passwordString: String) ->() -> Bool { 
     func isAuthUser() -> Bool { 

     client.invokeAPI("AuthenticateAndFetchData", 
         body: nil, 
         httpMethod: "GET", 
         parameters: ["userid": usernameString,"password":passwordString], 
         headers: nil) 
     { 
      (result, response, error) -> Void in 
      if let err = error { 
       print("ERROR ", err) 

      } else if let res = result { 



        let jsonArray = res as! NSArray 
        for value in jsonArray[0] as! NSDictionary { 
         let jsonstring = value.value as! String 
         NetworkService.jsonResponse = jsonstring 
         if let data = jsonstring.data(using: .utf8) { 
          if let content = try? JSONSerialization.jsonObject(with: data, options: []), 
           let array = content as? [[String: Any]] 
          { 
           for jsondict in array { 
            let auth = jsondict["IsAuth"]! as! String 
            self.isAuth = (auth == "true") ? true : false 
            let substring = NetworkService.parseJSONString(jsonString: jsonstring, key: "Activities") 
            let substring2 = NetworkService.parseJSONString(jsonString: substring(), key: "activityname") 
            let activityString = NetworkService.parseJSONvalue(jsonString:substring()) 
           } 
          } 
         } 
        } 
       } 
      } 
      return self.isAuth 
     } 
     return isAuthUser 

    } 

} 

我請登錄按鈕,此功能。但是當我用正確的憑證第一次按下按鈕時,此函數返回false,當我再次按下時,則完成處理程序已執行,它將isAuth更改爲true,並且該函數返回true。

所以,我必須按兩次按鈕才能進行身份驗證,我如何才能使它僅在第一次返回true。我希望在函數返回之前等待完成塊的執行。

+0

而不是從你的函數返回true或false。將其稱爲異步並將您的代碼放入完成處理程序 –

+0

感謝您的迴應。我是新來的迅速。你能幫我嗎我該怎麼稱呼功能異步。 –

回答

0

假設你的客戶端調用已異步並呼籲主隊列的完成處理程序,添加完成處理程序作爲一個額外的參數傳遞給你的方法:

func authenticateCredentials(usernameString: String, passwordString: String, completion: @escaping (Bool) -> Void){ 
    client.invokeAPI("AuthenticateAndFetchData", 
       body: nil, 
       httpMethod: "GET", 
       parameters: ["userid": usernameString,"password":passwordString], 
       headers: nil) { 
     ... 
     let auth = jsondict["IsAuth"]! as! String 
     let isAuth = (auth == "true") ? true : false 
     ... 
     completion(isAuth) 
    } 
} 

可以比這樣調用:

authenticateCredentials(usernameString: "user", passwordString: "pass") { (isAuth:Bool) in 
    self.isAuth = isAuth 
    // go on with whatever you want to do and use self.isAuth successfully 
} 
+0

完成需要bool作爲b參數或void? –

+0

xcode要求我在完成參數前添加@escaping –

+0

當我調用函數isAuth:Bool in self.isAuth = isAuth時,我沒有得到調用部分。它給編譯器錯誤。 –