2016-08-20 23 views
8

Tôi đang cố gắng để thêm xử lý lỗi trong việc tạo ra nút sử dụng trong dự án iOS sử dụng nhanh chóng và căn cứ hỏa lực:lỗi Xử lý ở New firebase và Swift

Dưới đây là đoạn code cho nút:

 @IBAction func Register(sender: AnyObject) { 

    if NameTF.text == "" || EmailTF.text == "" || PasswordTF.text == "" || RePasswordTF == "" || PhoneTF.text == "" || CityTF.text == "" 
    { 
     let alert = UIAlertController(title: "عذرًا", message:"يجب عليك ملىء كل الحقول المطلوبة", preferredStyle: .Alert) 
     alert.addAction(UIAlertAction(title: "نعم", style: .Default) { _ in }) 
     self.presentViewController(alert, animated: true){} 

    } else { 

     if PasswordTF.text != RePasswordTF.text { 
      let alert = UIAlertController(title: "عذرًا", message:"كلمتي المرور غير متطابقتين", preferredStyle: .Alert) 
      alert.addAction(UIAlertAction(title: "نعم", style: .Default) { _ in }) 
      self.presentViewController(alert, animated: true){} 

     } else { 


      FIRAuth.auth()?.createUserWithEmail(EmailTF.text!, password: PasswordTF.text!, completion: { user, error in 
       print(error) 

       if error != nil { 

        let errorCode = FIRAuthErrorNameKey 

        switch errorCode { 
        case "FIRAuthErrorCodeEmailAlreadyInUse": 
         let alert = UIAlertController(title: "عذرًا", message:"الإيميل مستخدم", preferredStyle: .Alert) 
         alert.addAction(UIAlertAction(title: "نعم", style: .Default) { _ in }) 
         self.presentViewController(alert, animated: true){} 

        case "FIRAuthErrorCodeUserNotFound": 
         let alert = UIAlertController(title: "عذرًا", message:"المستخدم غير موجود", preferredStyle: .Alert) 
         alert.addAction(UIAlertAction(title: "نعم", style: .Default) { _ in }) 
         self.presentViewController(alert, animated: true){} 

        case "FIRAuthErrorCodeInvalidEmail": 
         let alert = UIAlertController(title: "عذرًا", message:"الإيميل غير صحيح", preferredStyle: .Alert) 
         alert.addAction(UIAlertAction(title: "نعم", style: .Default) { _ in }) 
         self.presentViewController(alert, animated: true){} 

        case "FIRAuthErrorCodeNetworkError": 
         let alert = UIAlertController(title: "عذرًا", message:"خطأ في الاتصال بالانترنت", preferredStyle: .Alert) 
         alert.addAction(UIAlertAction(title: "نعم", style: .Default) { _ in }) 
         self.presentViewController(alert, animated: true){} 

        default: 
         let alert = UIAlertController(title: "عذرًا", message:"خطأ غير معروف", preferredStyle: .Alert) 
         alert.addAction(UIAlertAction(title: "نعم", style: .Default) { _ in }) 
         self.presentViewController(alert, animated: true){} 



        } 


       } else { 

        FIRAuth.auth()?.signInWithEmail(self.EmailTF.text!, password: self.PasswordTF.text!, completion: { (user: FIRUser?, error: NSError?) in 
         if let error = error { 
          print(error.localizedDescription) 
         } else { 

          self.ref.child("UserProfile").child(user!.uid).setValue([ 
           "email": self.EmailTF.text!, 
           "name" : self.NameTF.text!, 
           "phone": self.PhoneTF.text!, 
           "city" : self.CityTF.text!, 
           ]) 
          print("Sucess") 
          // self.performSegueWithIdentifier("SignUp", sender: nil) 

         } 
        }) 

       } //else 
      }) 

     } //Big else 


    } //Big Big else 
} 


}//end of 

tôi m không chắc chắn nếu cú ​​pháp của các lỗi trong báo cáo chuyển đổi là chính xác hay không!

Bởi vì khi tôi kiểm tra nó trong trình mô phỏng, nó luôn mang đến cho tôi trường hợp defualt không rõ lỗi! + tôi không thể tìm thấy cú pháp trong tài liệu: https://firebase.google.com/docs/auth/ios/errors

Vì vậy, cú pháp chính xác để thêm xử lý sử dụng căn cứ hỏa lực mới và nhanh chóng lỗi là gì!

+0

Side note - bạn không nên sử dụng 'báo cáo lớn if-else'. Chúng có thể thực sự khó hiểu trong mã của bạn. Đơn giản chỉ cần làm một cái gì đó như thế này: 'nếu NameFT.text ==" "... {return}' Bằng cách thêm 'return', bạn đang dừng thực hiện thêm. Để biết thêm, hãy xem [câu hỏi SO này] (http://stackoverflow.com/questions/37899049/where-does-this-line-of-code-return-to/37899267#37899267) – penatheboss

Trả lời

18

Tôi đã thực sự chỉ vật lộn với điều này trong một thời gian và tìm ra vấn đề là gì. Tôi đã thử mã được đăng trong một câu trả lời ở trên và dòng error.code đã cho tôi một lỗi. Nó đã làm việc với error._code mặc dù. Nói cách khác, tín dụng cho câu trả lời ban đầu cho Paul với một modificaiton nhẹ. Đây là mã cuối cùng của tôi (tôi sẽ chỉnh sửa nó cho tất cả các lỗi mặc dù):

if let errCode = FIRAuthErrorCode(rawValue: error!._code) { 

    switch errCode { 
     case .errorCodeInvalidEmail: 
      print("invalid email") 
     case .errorCodeEmailAlreadyInUse: 
      print("in use") 
     default: 
      print("Create User Error: \(error)") 
    }  
} 
+1

Trước khi bạn đăng câu trả lời ! Tôi đã cập nhật mã của tôi khi bạn đăng và nó hoạt động hoàn hảo! Cảm ơn bạn anyway! – Mariah

+0

Tuyệt vời! Tôi đã xem xét rất nhiều tài nguyên mà chỉ đề cập đến việc bạn có thể xử lý những lỗi này, nhưng không giải thích làm thế nào, tôi nghĩ rằng tôi đăng mã của tôi sau khi tôi đã nhận được nó. –

+0

Lưu ý trong Swift 3 tôi cần phải thực hiện một chuỗi chuyển tiếp của Lỗi tới NSError, để mã .code bị lộ ra, tức là. 'if let error = error là lỗi NSError? ... ' – xaphod

2

FIRAuthErrorCode là int enum không phải là chuỗi enum. Thực hiện như sau:

if let error = error { 
     switch FIRAuthErrorCode(rawValue: error.code) !{ 
       case .ErrorCodeInvalidEmail: 

Thông tin thêm trong số answer này.

4

Mặc dù điều này đã được trả lời một cách chính xác, muốn chia sẻ một thực hiện tốt đẹp cho này, chúng ta thêm vào dự án của chúng tôi.

Điều này có thể được thực hiện đối với các loại lỗi khác, nhưng chúng tôi chỉ cần nó cho FIRAuthErrorCodes.

Nếu bạn mở rộng FIRAuthErrorCode để có một ERRORMESSAGE biến kiểu chuỗi, bạn có thể có thông báo lỗi của riêng bạn cho người sử dụng:

extension FIRAuthErrorCode { 
    var errorMessage: String { 
     switch self { 
     case .errorCodeEmailAlreadyInUse: 
      return "The email is already in use with another account" 
     case .errorCodeUserDisabled: 
      return "Your account has been disabled. Please contact support." 
     case .errorCodeInvalidEmail, .errorCodeInvalidSender, .errorCodeInvalidRecipientEmail: 
      return "Please enter a valid email" 
     case .errorCodeNetworkError: 
      return "Network error. Please try again." 
     case .errorCodeWeakPassword: 
      return "Your password is too weak" 
     default: 
      return "Unknown error occurred" 
     } 
    } 
} 

Bạn có thể tùy chỉnh chỉ số như chúng tôi đã nêu trên và nhóm còn lại dưới " Lỗi không rõ".

Với phần mở rộng này, bạn có thể xử lý một lỗi như thể hiện trong câu trả lời Vladimir Romanov:

func handleError(_ error: Error) { 
    if let errorCode = FIRAuthErrorCode(rawValue: error._code) { 
     // now you can use the .errorMessage var to get your custom error message 
     print(errorCode.errorMessage) 
    } 
} 
+0

' errorCode' không có thành viên 'errorMessage' – Cesare

+0

@Cesare làm việc về phía tôi. Tâm trí chia sẻ nhiều mã của bạn hơn? – Andreas