I am trying to upload an image to Firebase and I actually succeeded several times yesterday, but today I'm getting this error:
Optional
- Some : Error Domain=FIRStorageErrorDomain Code=-13000 "An unknown error occurred, please check the server response." UserInfo={ResponseErrorDomain=FIRStorageErrorDomain, object=ProfileImages/ascascasc ascas.jpg, error_name=ERROR_USER_NOT_FOUND, bucket=ichallenge-c52ae.appspot.com, ResponseErrorCode=-13020, NSLocalizedDescription=An unknown error occurred, please check the server response.}
I want to reiterate: nothing was changed in the code between yesterday and today, it just stopped working. This is the code, I've highlighted the line where it happens with a comment:
#IBAction func signUpButtonPressed(sender: AnyObject)
{
// If textfields have more than 3 characters
if firstNameTextField.text!.characters.count > 3 && passwordTextField.text!.characters.count > 3 && emailTextField.text!.containsString("#")
{
createUser()
//Goes to Main Storyboard
parseOutdated.signUpInBackgroundWithBlock { (success: Bool, error: NSError?) in
NSNotificationCenter.defaultCenter().postNotificationName("Login", object: nil)
}
}
else
{
firstNameShake.shakeAnimation()
lastNameShake.shakeAnimation()
passwordShake.shakeAnimation()
emailShake.shakeAnimation()
}
}
func createUser()
{
//Unwrap optionals before pushing to Firebase Database
let name: String = "\(self.firstNameTextField.text!) \(self.lastNameTextField.text!)"
storeProfileImage(name)
}
func storeProfileImage(name: String)
{
let profileImageData = UIImageJPEGRepresentation(self.profileImageView.image!, 1.0)
// Create a reference to the file you want to upload
let profileImageRef = storageRef.child("ProfileImages/\(name).jpg")
// Upload the file to the path defined above
profileImageRef.putData(profileImageData!, metadata: nil) { metadata, error in
if (error != nil) //ERROR HAPPENS HERE
{
print("Image not stored: ", error?.localizedDescription)
}
else
{
//Stores the profile image URL and sends it to the next function
let downloadURL = metadata!.downloadURL()
self.storeUserData(name, profileImageURL: downloadURL!)
}
}
}
Here's a screenshot of the breakpoint in XCode:
Any help provided would be deeply appreciated.
If you have been testing with the same user witout signing out on your app, your authentication token might have expired. Try signing out firs
Related
So, I tried to add a delete account function using Firebase Manage User service here, it's showing me error. Below is the code.
#IBAction func deleteAccount() {
let user = Auth.auth().currentUser
var credential: AuthCredential
user?.reauthenticate(with: credential) { error in
if let error = error {
self.redAlert(message: "Unable to authenticate. Please try again.")
} else {
Auth.auth().currentUser?.delete { error in
if let error = error {
self.redAlert(message: "An error happened. Please contact support to delete your account")
} else {
self.greenAlert(message: "Your account has been deleted")
}
}
}
}
Attached the screenshot as well.
It keeps showing "Contextual closure type '(AuthDataResult?, Error?) -> Void' expects 2 arguments, but 1 was used in closure body" which I really don't know how to fix it. Would you mind helping to pinpoint this?
Screenshot
EDIT: I actually found the solution. The right code should be:
#IBAction func deleteAccount(_send: Any) {
let user = Auth.auth().currentUser
let emailText: String = email.text!
let passwordText: String = password.text!
var credential: AuthCredential = EmailAuthProvider.credential(withEmail: emailText, password: passwordText)
user?.reauthenticate(with: credential, completion: { (result, error) in
if let error = error {
self.redAlert(message: "Unable to authenticate. Please try again.")
} else {
Auth.auth().currentUser?.delete { error in
if let error = error {
self.redAlert(message: "An error happened. Please contact support to delete your account")
} else {
self.greenAlert(message: "Your account has been deleted")
self.stopLoading()
self.logout()
}
}
}
})
}
Hope it helps anyone that is struggling!
I have the following code in an intent handler for a widget I am creating:
extension FileManager {
static var appGroupURLAsText: String {
`default`.containerURL(forSecurityApplicationGroupIdentifier: "group.com.emojiApp.EmojiWidget")!.absoluteString
}
}
extension IntentHandler: SelectEmojiIntentHandling {
func provideEmojiOptionsCollection(
for intent: SelectEmojiIntent,
with completion: #escaping (INObjectCollection<EmojiINO>?, Error?) -> Void
) {
print("stuff happening in intent handler")
print(FileManager.appGroupURLAsText)
let fm = FileManager.default
print("after declaring fm")
var items = [String]()
do {
print("inside of do")
items = try fm.contentsOfDirectory(atPath: FileManager.appGroupURLAsText)
print("after declaring items")
} catch {
print("Unexpected error: \(error).")
// failed to read directory – bad permissions, perhaps?
}
//I don't believe the code below is relevant to the error but I'm including it here in case
var emojiItems = [EmojiINO]()
for item in items {
let finalThing = EmojiINO(identifier: item, display: item)
emojiItems.append(finalThing)
}
completion(INObjectCollection(items: emojiItems), nil)
}
}
When I run the code in an iphone 13 pro simulator with ios 15.5, I get the following output:
stuff happening in intent handler
file:///Users/myname/Library/Developer/CoreSimulator/Devices/86836E5F-4CA8-4288-899F-0CA595F18525/data/Containers/Shared/AppGroup/4AD329B4-32C5-40EE-BEBF-BFC2BDDB34F9/
after declaring fm
inside of do
Unexpected error: Error Domain=NSCocoaErrorDomain Code=260 "The folder “4AD329B4-32C5-40EE-BEBF-BFC2BDDB34F9” doesn’t exist." UserInfo={NSUserStringVariant=(
Folder
),
It never gets to the after declaring items print statement so I know the issue is something with contentsOfDirectory . I know the folder is there though because appGroupUrl is returning a valid folder and I checked in my finder and the folder is there. How do I fix this?
So it turns out I should have used path instead of absoluteString.
So just change line 3 to this:
`default`.containerURL(forSecurityApplicationGroupIdentifier: "group.com.emojiApp.EmojiWidget")!.path
The CKContainer.discoverAllIdentities request always fails in my CloudKit app. It has continually failed over the course of several days.
A simplified version of the code that is failing (which results in the same error) is:
private func getContacts(completion: (([CKUserIdentity]?) -> Void)?) {
container.status(forApplicationPermission: .userDiscoverability) { [weak self] status, error in
if let error = error {
print(error)
}
switch status {
case .granted:
self?.discover(completion: completion)
default:
print("status not granted")
}
}
}
private func discover(completion: (([CKUserIdentity]?) -> Void)?) {
let op = CKDiscoverAllUserIdentitiesOperation()
op.qualityOfService = .userInitiated
op.discoverAllUserIdentitiesCompletionBlock = { error in
if let error = error {
print(error)
}
}
op.userIdentityDiscoveredBlock = { identity in
print(identity)
}
op.start()
}
It results in an error being passed to the op.discoverAllUserIdentitiesCompletionBlock. The description of the error in the log is:
<CKError 0x1c4a51a60: "Server Rejected Request" (15/2000); server message = "Internal server error"; uuid = F67453B9-712D-4E5E-9335-929123E3C978; container ID = "iCloud.com.huntermaximillionmonk.topdraw">
Previously, this operation would work, but only for certain iCloud users. Now it's not for both of my test users.
Problem:
This was a problem in iOS 11.0
Based on my testing:
This works ok in Xcode 9.2 / iOS 11.2.1 on the device (not simulator)
After resetting the simulator works for the first time, doesn't work subsequently, however on the device it works repeatedly.
Code:
let queue = OperationQueue()
func requestPermissions(for permissions: CKApplicationPermissions,
completionHandler: #escaping (CKApplicationPermissionStatus, Error?) -> ()) {
CKContainer.default().requestApplicationPermission(permissions) { status, error in
if let error = error {
print("Error for requesting \(permissions) - \(error)")
}
let statusMessage : String
switch status {
case .granted:
statusMessage = "Granted"
case .denied:
statusMessage = "Denied"
case .couldNotComplete:
statusMessage = "Could not complete"
case .initialState:
statusMessage = "Initial state"
}
print("Permission - \(statusMessage)")
completionHandler(status, error)
}
}
private func discoverAllUsers() {
let operation = CKDiscoverAllUserIdentitiesOperation()
operation.userIdentityDiscoveredBlock = { userIdentity in
print("userIdentity = \(userIdentity)")
}
operation.discoverAllUserIdentitiesCompletionBlock = { error in
if let error = error {
print("Discover all users Error: \(error) ")
}
else {
print("Discover all users completed successfully")
}
}
queue.addOperation(operation)
}
Edit:
Apple fixed this issue day after this answer was posted, coincidence?! I don't think so :)
This is not actually the answer to the question, but a fix that helped me to cross over this error. It will require you to change your app UI interaction and add ContactsUI framework to your project, moreover your user will be responsible for selecting a contact with iCloud related email.
Good news is that the method discoverUserIdentity is still works. So, you can use it to get CKUserIdentity from manually selected contact.
func addContact(_ contact:CNContact) {
var lookUpEmails = [CKUserIdentityLookupInfo]()
for email in contact.emailAddresses {
lookUpEmails.append(CKUserIdentityLookupInfo(emailAddress: (email.value as String)))
}
let checkUserOperation = CKDiscoverUserIdentitiesOperation()
checkUserOperation.userIdentityLookupInfos = lookUpEmails
checkUserOperation.userIdentityDiscoveredBlock = { [unowned self] (identity, info) -> Void in
if identity.hasiCloudAccount {
if let recordID = identity.userRecordID {
//do something with discovered user
}
checkUserOperation.cancel()
}
}
checkUserOperation.queuePriority = Operation.QueuePriority.high
CKContainer.default().add(checkUserOperation)
}
It might sound useless, but in my case, it helped me to solve the Server Rejected Request" (15/2000) error, to fix one of the features of my app and continue to use the other feature related code with less efforts than I thought.
I hope someone will find this helpful.
Just another data point on this that might help with the overall picture. I was still seeing this error on 11.2.5 when I used my own iCloud AppleID (with hundreds of contacts) while running a Test App that called discoverAllIdentitiesWithCompletionHandler. I'd get the dreaded
CKError 0x1c0051730: "Server Rejected Request" (15/2000); server message = "Internal server error".
When I switched to run the exact same code on my daughters iOS11.2.5 device (with just a handful of contacts) the code worked fine.
Leads me to believe there is some rate limiting going on when there are a lot of contacts with iOS11.
(P.S. No errors at all running on iOS10)
I am using the latest Facebook SDK and I get this error when I run the block of code below: Facebook signup error - The operation couldn’t be completed. (com.facebook.sdk.login error 308.)
Here is my code:
func signupWithFacebook() {
FBSDKLoginManager().logIn(withReadPermissions: ["public_profile"], from: self) { (result, error) in
if let error = error {
print("Facebook signup error - \(error.localizedDescription)")
} else if result != nil {
let credential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
self.facebookSignup = true
self.addUserToAuth(credential, twitterUserID: "")
}
}
}
I Figured it out! It has to do with the way Apple deals with Keychain. All you have to do is go into the "Compatibilities" tab under the target for your app and turn "Keychain Sharing" on. Here is a more fulfilling answer.
Im using SMS verification to verify users. My problem is that when I enter a code to verify I get invalid code. I can't for the life of me figure out why.
Calling cloud code function:
#IBAction func verifyCodeButtonTapped(sender: AnyObject) {
var verificationCode: String = verificationCodeTextField.text!
let textFieldText = verificationCodeTextField.text ?? ""
if verificationCode.utf16.count != 4 {
displayAlert("Error", message: "You must entert the 4 digit verification code sent yo your phone")
} else {
let params = ["verifyPhoneNumber" : textFieldText]
PFCloud.callFunctionInBackground("verifyPhoneNumber", withParameters: params, block: { (object: AnyObject?, error) -> Void in
if error == nil {
self.performSegueWithIdentifier("showVerifyCodeView", sender: self)
} else {
self.displayAlert("Sorry", message: "We couldnt verify you. Please check that you enterd the correct 4 digit code sent to your phone")
}
})
}
}
Cloud code to verify code:
Parse.Cloud.define("verifyPhoneNumber", function(request, response) {
var user = Parse.User.current();
var verificationCode = user.get("phoneVerificationCode");
if (verificationCode == request.params.phoneVerificationCode) {
user.set("phoneNumber", request.params.phoneNumber);
user.save();
response.success("Success");
} else {
response.error("Invalid verification code.");
}
});
Twilio developer evangelist here.
In the Parse code, you are expecting request.params.phoneVerificationCode but when you call the cloud function from iOS you let params = ["verifyPhoneNumber" : textFieldText].
So, either change that line to
let params = ["phoneVerificationCode" : textFieldText]
so that it matches the cloud code. Or change your cloud code to
if (verificationCode == request.params.verifyPhoneNumber) {
so that it matches the iOS code.