是否可以在委托方法中使用完成处理程序 - Swift
Posted
技术标签:
【中文标题】是否可以在委托方法中使用完成处理程序 - Swift【英文标题】:Is it possible to use completion handler in delegate method - Swift 【发布时间】:2018-04-28 18:54:41 【问题描述】:我正在尝试在单例助手类中处理“谷歌登录”。
我有 LoginHelper,以及一个使用完成处理程序处理登录的方法。如您所知,Google Sign 有委托方法。当调用委托方法时,我需要通知我的完成处理程序。我不确定,有可能吗?
让我们一起集思广益或帮助我。
我的方法如下;
@objc func googleLoginPressed(viewController:UIViewController, isLoginSuccessfull:(Bool) -> ())
GIDSignIn.sharedInstance().signIn()
【问题讨论】:
这里的“委托方法”在哪里?展示一下,然后我们可以讨论如何将isLoginSucessfull
传递给它。
【参考方案1】:
是的,有可能
你必须设置 typeable:
public typealias isCompletion = (_ isConnected: Bool?) -> Void
并在类中添加这样的变量:
var completion: isCompletion?
你的方法是这样的:
func googleLoginPressed(viewController:UIViewController, isLoginSuccessfull:@escaping isCompletion)
completion = isLoginSuccessfull
GIDSignIn.sharedInstance().signIn()
登录后委托方法将调用,然后这样做:
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!)
if let error = error
print("\(error.localizedDescription)")
else
completion(true)
或者
您可以使用协议来做到这一点:
import UIKit
import GoogleSignIn
/// delegates to handle success and failure response of google sign-in
protocol LoginWithGoogleDelegate: class
func didSucceedToSignInFor(user: UserModel)
func didFailToSignIn(error: Error)
/// separate class for google sign-in methods
class LoginWithGoogle: NSObject
// MARK: - Properties
static let sharedInstance = LoginWithGoogle()
weak var delegate: LoginWithGoogleDelegate?
var globalViewController: UIViewController?
// MARK: - Helper Methods
/**
configures the settings of google sign-in sdk
- parameter viewController: it is the view controller on which we have to show the google sign-in screen
*/
func configureGooglePlus(viewController: UIViewController)
globalViewController = viewController
GIDSignIn.sharedInstance().clientID = Configuration.GoogleSignIn.clientID
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().signIn()
// MARK: - GIDSignInDelegate methods
extension LoginWithGoogle: GIDSignInDelegate
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!)
if let error = error
print("\(error.localizedDescription)")
self.delegate?.didFailToSignIn(error: error)
else
// Perform any operations on signed in user here.
var googleUser = UserModel()
googleUser.googlePlusId = user.userID
googleUser.googlePlusToken = user.authentication.idToken
googleUser.fullName = user.profile.name
googleUser.email = user.profile.email
//send the user details through LoginWithGoogleDelegate method
self.delegate?.didSucceedToSignInFor(user: googleUser)
func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!)
print("Something Went Wrong")
self.delegate?.didFailToSignIn(error: error)
【讨论】:
以上是关于是否可以在委托方法中使用完成处理程序 - Swift的主要内容,如果未能解决你的问题,请参考以下文章
C#如何使用异步编程BeginInvoke/EndInvoke