我正在尋找在某些錯誤代碼出現在我的程序中時創建某些事件。例如,如果有錯誤代碼200,我需要讓用戶知道他們錯過了用戶名字段。或者對於錯誤代碼125,我需要讓他們知道在創建帳戶時他們沒有輸入有效的電子郵件地址。我如何專門針對這些錯誤代碼?我試過下面的代碼沒有成功,我做錯了什麼,這可能嗎?在解析中處理某些錯誤
if error.code == 125 {
var invalidEmail:UIAlertView = UIAlertView(title: Please try again, message: "That does not look like a real email address. Please enter a real one.", delegate: self, cancelButtonTitle: "Try again")
invalidEmail.show()
}
xCode告訴我的錯誤是我有一個無法解析的標識符'錯誤'。在解析啓動器項目文件'AppDelegate.swift'中有一個這樣的實例,它調用以下代碼,它似乎很好地工作。
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
println("Push notifications are not supported in the iOS Simulator.")
} else {
println("application:didFailToRegisterForRemoteNotificationsWithError: %@", error)
}
}
我的代碼
@IBAction func signupTapped(sender: AnyObject) {
let fullname = fullnameField.text
let email = emailField.text
let username = usernameField.text
let password = passwordField.text
var user = PFUser()
user.username = username
user.password = password
user.email = email
// other fields can be set just like with PFObject
user["fullname"] = fullname
if error.code == 125 {
let alert = UIAlertController(title: "Please try again", message: "That does not look like a valid email address.", preferedStyle: .Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
presentViewController(alert, animated: true)
}
if fullname.isEmpty || email.isEmpty || username.isEmpty || password.isEmpty {
let emptyFieldsError:UIAlertView = UIAlertView(title: "Please try again", message: "Please fill out all the fields so that we can create your account.", delegate: self, cancelButtonTitle: "Try again")
emptyFieldsError.show()
}
user.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
if let error = error {
let errorString = error.userInfo?["error"] as? NSString
// Show the errorString somewhere and let the user try again.
} else {
// Hooray! Let them use the app now.
}
}
}
你忘了打電話給'show'消息嗎? – tounaobun
你的'UIAlertView'似乎不會調用'show',而這正是不推薦使用的。 – Larme
我已根據收到的意見對我所做的實現進行了更改。 –