2017-11-22 3 views
0

첫 번째 Swift/iOS 애플리케이션을 구축 중입니다. 현재 데이터베이스 용으로 Firebase를 사용하고 있습니다.값이있는 모든 속성에도 불구하고 '선택 값을 언 래핑하는 동안 예기치 않게 nil이 발견되었습니다'

fatal error: unexpectedly found nil while unwrapping an Optional value 

나는 물체를 보면, 모든 재산 :

내가 가입 양식을 작성 후 등록 버튼을 눌렀을 때, 나는 다음과 같은 오류가 발생 초조 한 문제를 직면했습니다 그 가치가있는 것 같습니다. 내 Firebase 가입 기능은 다음과 같습니다.

func handleRegister() { 
     if let email = emailTextField.text, let password = passwordTextField.text, let fullName = fullNameTextField.text, let age = Int(ageTextField.text!), let username = userNameTextField.text { 

      Auth.auth().createUser(withEmail: email, password: password) { (user, error) in 
       // ... 

       if let firebaseError = error { 
        print(firebaseError.localizedDescription) 
        return 
       } 

       let userID = user!.uid 

       //Instantiate our User model - set key values equal to optionals above from sign up form 
       let userAccount = User(userId: userID, email: email, fullName: fullName, age: age, username: username) 

       //Initialize an empty dictionary to hold the keys and values to upload to Firebase 
       var userAccountDict = [String:AnyObject]() 

       //Use a dictionary method to update the keys and matching values. The values are the ones from UserAccount model's properties and the keys are what we decide we want them to be named in FirebaseDatabase. Use these keys to extract the values 
       userAccountDict.updateValue(userAccount.userId as AnyObject, forKey: "userId") 
       userAccountDict.updateValue(userAccount.email as AnyObject, forKey: "email") 
       userAccountDict.updateValue(userAccount.fullName as AnyObject, forKey: "fullName") 
       userAccountDict.updateValue(userAccount.age as AnyObject, forKey: "age") 
       userAccountDict.updateValue(userAccount.username as AnyObject, forKey: "username") 


       //Upload dictionary with the keys and values set above. The database will hold these key/value pairs under the "users" node. 
       self.ref.child("users").child(user!.uid).setValue(userAccountDict) 
       print("User registered in Firebase with a userId of " + user!.uid) 


      } 
     } 
    } 

가입 프로세스는 현재 스토리 보드와 달리 프로그래밍 방식으로 수행됩니다. 이 enter image description here

내가 볼 수있는 유일한 것은 그 무기 호입니다 : 여기

// REGISTER BUTTON 
    let registerButton: UIButton = { 
     let button = UIButton(type: UIButtonType.system) 
     button.isHidden = true 
     button.isEnabled = false 
     button.backgroundColor = UIColor.red 
     button.setTitle("Register", for: UIControlState.normal) 
     button.setTitleColor(.white, for: UIControlState.normal) 
     button.titleLabel?.font = UIFont(name: "Futura", size: 16) 
     button.layer.cornerRadius = 5 
     button.clipsToBounds = true 
     button.translatesAutoresizingMaskIntoConstraints = false 

     button.addTarget(self, action: #selector(handleRegister), for: .touchUpInside) 
     button.addTarget(self, action: #selector(toAppFeed), for: UIControlEvents.touchUpInside) 


     return button 
    }() 

내가 내 콘솔 옆에 왼쪽 창에 표시됩니다 : 여기에 내가 궁극적으로() 함수 내 handleRegister 호출 버튼입니다 Firebase이 아무 것도 던지지 않기 때문에 내가 상상해야하는 오류입니다. 그럼에도 불구하고 내가 Firebase에 게시 할 대상에 없습니다. Firebase를 확인하면 생성 한 모든 사용자를 볼 수 있지만 handleRegister() 함수에서 수집 한 사용자 데이터는 데이터베이스에 저장되지 않습니다.

필자는 몇 달 전부터 Firebase를 사용 해왔고 이전에는이 ​​문제에 직면하지 않았습니다. 다른 질문을 살펴 보았지만 아무도이 특정 문제를 해결할 수 없습니다. 이 시점에서 유일하게 생각할 수있는 것은 handleRegister()가 호출 될 때 무언가가 여전히 남아 있고 나중에 값을 얻는 것입니다. 그러나 나는 확실하지 않다.

대단히 감사합니다.

편집 - 오류가 표시 곳 여기 후 양식을 작성 후 누르면 '등록'그러나 그 열쇠는, enter image description here

+3

오류가 발생한 줄은 무엇입니까? – Connor

+0

'userAccountDict.updateValue (AnyObject로 userAccount.userId, forKey : "userId")'대신 Swift 사전 구문을 사용해야합니다 :'userAccountDict [ "userId"] = userAccount.userId' 충돌을 일으키는 원인이 무엇입니까 – Connor

+0

handle 비동기 적 방법으로 등록 완료 처리기를 사용해야합니다 –

답변

0

뭔가 실제로 언 래핑되었지만 내 변수가 아닙니다. ?

중포 기지의 참조가 처음 self.ref.child에서

ref: DatabaseReference! 

로 설정되어, 심판은 필요 :

self.ref?.child 

은 물론, 콘솔은 모든 것을 너무 잘 공개하지 않았다. 그래서 심판은 풀려 있지 않은 상태 였고, handleRegister() 함수에서 사용할 때 존재하는지 확인하지 않았습니다.

viewDidLoad()에서 Firebase 참조를 인스턴스화하는 것을 잊었습니다.

-1

당신은 키 참조하여 사전에 값을 할당하려는를 아직 사용할 수 없으며 그게 문제라고 생각합니다.

여기에 솔루션 var에 userAccountDict = [문자열 : 모든]()의

userAccountDict [ "사용자 ID"] = userAccount.userId 등등 ...

행운을 빕니다 :)

+0

그것이 바로 충돌을 일으키는 것이므로 키를 사용할 수 없다는 것을 언급하고 키의 값을 업데이트하려고합니다. –

+0

새 사용자를 만들 때 다른 테스트 프로젝트에서이 메서드를 사용 했으므로 이상하게 들릴 것입니다. 나는 그것을 쏜다. 감사합니다 – sharedev

+0

그냥 시도 - 불행히도 작동하지 않았다 : / – sharedev

관련 문제