gpt4 book ai didi

ios - 在同步调用中执行异步任务

转载 作者:行者123 更新时间:2023-11-28 16:13:45 25 4
gpt4 key购买 nike

我想注册一个异步执行的用户。但是,调用函数的行为是同步的,因为程序只应在成功创建用户后继续。当前的实现是:

class SignUp: NSObject {

// ...

func signUpUser() throws -> Bool {
guard hasEmptyFields() else {
throw CustomErrorCodes.EmptyField
}

guard isValidEmail() else {
throw CustomErrorCodes.InvalidEmail
}

createUser( { (result) in
guard result else {
throw CustomErrorCodes.UserNameTaken
}
return true // Error: cannot throw....
})
}


func createUser( succeeded: (result: Bool) -> () ) -> Void {
let newUser = User()
newUser.username = username!
newUser.password = password!

// User is created asynchronously
createUserInBackground(newUser, onCompletion: {(succeed, error) -> Void in
if (error != nil) {
// Show error alert
} else {
succeeded(result: succeed)
}
})

}

}

在 ViewController 中,注册是按如下方式启动的:

do {
try signup.signUpUser()
} catch let error as CustomErrorCodes {
// Process error
}

但是,这不起作用,因为 createUser 不是一个抛出函数。如何确保 signUpUser() 仅在成功创建新用户时返回 true?

最佳答案

你说:

and in a ViewController the signup is initiated as follows:

do {
try signup.signUpUser()
} catch let error as CustomErrorCodes {
// Process error
}

但是不要。这不是异步的工作方式。整个想法是您不要等待。如果您正在等待,则它不是异步的。这意味着你在阻止,而这正是你不能做的。

相反,安排在异步过程结束时回调。那时你会听到事情成功与否。查看下载任务委托(delegate)的结构:

https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionDownloadTask_class/

下载任务回调委托(delegate),让它知道我们是否成功完成。这就是您希望与异步任务建立的关系。你想成为那个代表。

关于ios - 在同步调用中执行异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39308488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com