Firebase Authentication with phoneNumber failed with Internal error - swift

I want to use Firebase SMS Authentication with phone number.
I have already enabled push notification in my app setting and registered Firebase Apns authentication key as google document says.
However, after I sent phone number with country code, Xcode says,
Failed to receive remote notification to verify app identity within 5
second(s)
Error says as below:
error: Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information., NSUnderlyingError=0x28329c8a0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 500;
errors = (
{
domain = global;
message = "Internal error encountered.";
reason = backendError;
}
);
message = "Internal error encountered.";
status = INTERNAL;
}}}}
My code:
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { verificationId, error in
if let error = error {
print("error: \(error)")
return
}
print("verificationId: \(verificationId!)")
UserDefaults.standard.set(verificationId, forKey: "authVerificationID")
self.goToSecondVC()
}
Any idea??

Related

How to handle connection loss uploading to Firebase iOS?

I have a frontend Swift application in which users are to upload large videos and photos to Firebase Storage. I am currently working on error handling. The documentation does a good job of explaining error handling from Google's sever side of things, however it does not cover how to deal with connection loss.
This is the error handling directly from the documentation:
...
// Upload file and metadata to the object 'images/mountains.jpg'
let uploadTask = storageRef.putFile(from: localFile, metadata: metadata)
uploadTask.observe(.failure) { snapshot in
if let error = snapshot.error as? NSError {
switch (StorageErrorCode(rawValue: error.code)!) {
case .objectNotFound:
// File doesn't exist
break
case .unauthorized:
// User doesn't have permission to access file
break
case .cancelled:
// User canceled the upload
break
/* ... */
case .unknown:
// Unknown error occurred, inspect the server response
break
default:
// A separate error occurred. This is a good place to retry the upload.
break
}
}
}
I have done some tests on my device where the upload begins with no network connection. The following gets automatically printed to the console every second or so after the network goes down:
2020-07-06 01:38:28.361559-0700 Rage[12281:1978025] Connection 9: failed to connect 1:50, reason -1
2020-07-06 01:38:28.361648-0700 Rage[12281:1978025] Connection 9: encountered error(1:50)
2020-07-06 01:38:28.366906-0700 Rage[12281:1978025] Task <320E9387-F725-4AEA-B3BE-76425F73F9F7>.<6> HTTP load failed, 0/0 bytes (error code: -1009 [1:50])
2020-07-06 01:38:28.368381-0700 Rage[12281:1978042] Task <320E9387-F725-4AEA-B3BE-76425F73F9F7>.<6> finished with error [-1009] Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={_kCFStreamErrorCodeKey=50, NSUnderlyingError=0x280a581e0 {Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={_kCFStreamErrorCodeKey=50, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <320E9387-F725-4AEA-B3BE-76425F73F9F7>.<6>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <320E9387-F725-4AEA-B3BE-76425F73F9F7>.<6>"
), NSLocalizedDescription=The Internet connection appears to be offline., NSErrorFailingURLStringKey=https://firebasestorage.googleapis.com/v0/b/rage-5940.appspot.com/o/event%2FBEC3B24F-5F97-4B6A-8FD3-5DC2F7D37AFB.mp4?uploadType=resumable&name=event%2FBEC3B24F-5F97-4B6A-8FD3-5DC2F7D37AFB.mp4, NSErrorFailingURLKey=https://firebasestorage.googleapis.com/v0/b/rage-5940.appspot.com/o/event%2FBEC3B24F-5F97-4B6A-8FD3-5DC2F7D37AFB.mp4?uploadType=resumable&name=event%2FBEC3B24F-5F97-4B6A-8FD3-5DC2F7D37AFB.mp4, _kCFStreamErrorDomainKey=1}
Is this Firebase throwing these errors? If so they are probably being thrown trying to create a storageRef before the uploadTask could even begin, and thus escape any provided error handling.
Is there anyway to catch these network errors?
Did you try this?
if error._code == NSURLErrorNetworkConnectionLost {
}
there are a couple of more you can check with them:
NSURLErrorTimedOut
NSURLErrorNotConnectedToInternet
NSURLErrorCannotConnectToHost

SSAccountStore: Unable to get the local account. error = Error Domain=SSErrorDomain Code=100

I am having trouble getting access to the users Apple Music.
The error I am getting is
[core] "Error returned from daemon: Error Domain=com.apple.accounts Code=9 "(null)""
2019-02-04 19:14:37.250467+0900 SSAccountStore: Failed to fetch the backing accounts. error = Error Domain=com.apple.accounts Code=9 "(null)"
2019-02-04 19:14:37.252008+0900 [core] "Error returned from daemon: Error Domain=com.apple.accounts Code=9 "(null)""
2019-02-04 19:14:37.252051+0900 SSAccountStore: Failed to fetch the backing accounts. error = Error Domain=com.apple.accounts Code=9 "(null)"
2019-02-04 19:14:37.253604+0900 SSAccountStore: Unable to get the local account. error = Error Domain=SSErrorDomain Code=100 "Cannot connect to iTunes Store" UserInfo={NSLocalizedDescription=Cannot connect to iTunes Store}
However the weird part of this code is that I am also able to retrieve the Music User Token.
Is there sth that I am missing?
Any help is appreciated.
static func auth(){
let cloudServiceController = SKCloudServiceController()
let developerToken = "abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyz"
SKCloudServiceController.requestAuthorization { status in
guard status == .authorized else { return }
}
cloudServiceController.requestCapabilities { capabilities, error in
guard capabilities.contains(.musicCatalogPlayback) else { return }
}
cloudServiceController.requestUserToken(forDeveloperToken: developerToken, completionHandler: { token, error in
guard let token = token else { return }
UserDefaults.standard.set(token, forKey: "MUSIC_USER_TOKEN")
UserDefaults.standard.set(developerToken, forKey: "DEVELOPER_TOKEN")
print("Music User Token:", token)
})
}
I think you have to call
cloudServiceController.requestUserToken
once user has authorised after completion handler for SKCloudServiceController.requestAuthorization
I was having this same issue until I removed Bearer from the beginning of developerToken.
OP's code example has developerToken set to "abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyz", so I can only assume if OP is including Bearer at the beginning or not.
So to be more clear, this is what I was doing before:
asyncAskMyServerToGenerateMyAppleMusicDeveloperJWTDevToken { rawDevToken in
let formattedDeveloperToken = "Bearer \(rawDevToken)"
SKCloudServiceController().requestUserToken(forDeveloperToken: formattedDeveloperToken)
{ possibleToken, _ in
if let userMusicToken = possibleToken
{
YayIGotIt.forTheWin(userMusicToken)
}
}
}
And this is what I did to make it actually work:
asyncAskMyServerToGenerateMyAppleMusicDeveloperJWTDevToken { rawDevToken in
//Not prepending "Bearer " anymore
SKCloudServiceController().requestUserToken(forDeveloperToken: rawDevToken)
{ possibleToken, _ in
if let userMusicToken = possibleToken
{
YayIGotIt.forTheWin(userMusicToken) //This actually fires now
}
}
}

Firebase FireAuthErrorCode when email address is empty

I'm implementing FireAuth error codes for firebase email and password signup, they all work except in 2 cases. When the email address field is empty, case .errorCodeInvalidEmail is called. When i type some letters (no valid email address), the default case is called. For the password field, it's the other way around. When i type one character the case .ErrorCodeWeakPassword" is called. When i leave the field empty, i go to the default case.
this is my code:
#IBAction func SignInButtonPressed(_ sender: LogInVcButton) {
if let email = emailField.text, let password = pwdField.text {
FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { (user, error) in
if error == nil {
print("Email User Authenticated with Firebase")
} else {
FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
if let errCode = FIRAuthErrorCode(rawValue: (error?._code)!) {
switch errCode {
case .errorCodeEmailAlreadyInUse: self.errorMessage(message: "Email address is already in use")
case .errorCodeInvalidEmail: self.errorMessage(message: "Email address is invalid")
case .errorCodeWrongPassword: self.errorMessage(message: "Wrong password")
case .errorCodeWeakPassword: self.errorMessage(message: "Password needs to be minimum 6 characters")
// TODO: A case for if the password field is blank
default: print("default")
}
} else {
print("Successfully Authenticated with Firebase")
}
}
})
}
})
}
}
I don't see which error code would handle the wrong email format or the empty password field in the docs. I can try to handle them my own, but i would think firebase would cover these cases ? https://firebase.google.com/docs/auth/ios/errors
Anyone can help me out ?
edit: after digging in some deeper i managed to print out the firebase descriptions of the errors.
if i pres sign in with emailAddress and password empty:
Optional(Error Domain=FIRAuthErrorDomain Code=17008 "The email address is badly formatted." UserInfo={NSLocalizedDescription=The email address is badly formatted., error_name=ERROR_INVALID_EMAIL})
case .errorCodeInvalidEmail is called. this is ok
When i write an invalid email address and empty password empty i get:
Optional(Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x6080000565c0 Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 400;
errors = (
{
domain = global;
message = "MISSING_PASSWORD";
reason = invalid;
}
);
message = "MISSING_PASSWORD";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.})
NOK .errorCodeInternalError: It says missing password, but it should check the email address
When i type an invalid email address and one character in the password field i get:
Optional(Error Domain=FIRAuthErrorDomain Code=17008 "The email address is badly formatted." UserInfo={NSLocalizedDescription=The email address is badly formatted., error_name=ERROR_INVALID_EMAIL})
This seems ok
when i type a valid email address and no password:
Optional(Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x6080000565c0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 400;
errors = (
{
domain = global;
message = "MISSING_PASSWORD";
reason = invalid;
}
);
message = "MISSING_PASSWORD";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.})
NOK. .errorCodeInternalError
when i type a valid email address and one character in the pw field
Optional(Error Domain=FIRAuthErrorDomain Code=17026 "The password must be 6 characters long or more." UserInfo={NSLocalizedDescription=The password must be 6 characters long or more., error_name=ERROR_WEAK_PASSWORD, NSLocalizedFailureReason=Password should be at least 6 characters})
.errorCodeWeakPassword is called. This is ok too. and should also be the case on point 5 imo
When i type no email and a valid password
Optional(Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x600000053ce0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 400;
errors = (
{
domain = global;
message = "MISSING_EMAIL";
reason = invalid;
}
);
message = "MISSING_EMAIL";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.})
NOK Internal Error is called. Why not same as in point 1 ?

Getting lots of CloudKit errors (500) all of a sudden

Nearly everything my app does in CloudKit now returns this error:
<CKError 0x14ecff70: "Server Rejected Request" (15/2001); "Request failed with http status code 500">
(lldb) po [error userInfo]
{
CKDHTTPHeaders = {
Connection = close;
"Content-Length" = 0;
"X-Apple-Request-UUID" = "F8E4C91A-5F72-4792-9F13-BB5FBB10BA8E";
"X-Responding-Instance" = "ckdatabaseservice:32400203:mr11p24ic-ztbu11100101:8103:15B153:16274";
};
CKHTTPStatus = 500;
NSDebugDescription = "CKInternalErrorDomain: 2001";
NSLocalizedDescription = "Request failed with http status code 500";
NSUnderlyingError = "<CKError 0x14d5af70: \"Unknown Error\" (2001)>";
}
Any ideas why this could be happening? I'm tempted to blame it on temporary CloudKit server issues (which is how I would want to interpret an error 500)...but I don't know if that's appropriate.
This is a bug on the iCloud server that's affecting your container. I've grabbed logs from that request and the server team will clean up your container soon. In the meantime you can use a different container name for testing.
If you'd like to file a radar for this we can let you know when the container gets cleaned up.

Stop query if there Is an error (Parse.com)

At the moment the app it crashing if there is no internet connection when running the query. How do I tell the query to stop if there is an error and prevent this?
Thanks
Error Below:
Error: Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo=0x1702e0d80 {NSUnderlyingError=0x1742569e0 "The Internet connection appears to be offline.", NSErrorFailingURLStringKey=https://api.parse.com/2/find, NSErrorFailingURLKey=https://api.parse.com/2/find, _kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8, NSLocalizedDescription=The Internet connection appears to be offline.} (Code: 100, Version: 1.2.21)
2014-12-01 20:36:39.257 AppName[5903:999805] Network connection failed. Making attempt 2 after sleeping for 1.546502 seconds.
In parse there you can handle errors for many things.
I think to stop a query if there is not internet connection you can use kPFErrorConnectionFailed
Ex.
var query = PFQuery()
query.findObjectsInBackgroundWithBlock{
(success:Bool!, error:NSError!)-> Void in
if (error == nil) {
//continue query
}
else{
if(error.code == kPFErrorConnectionFailed) {
//handle error
}
}
}