I have been trying to get FireStore to work on Swift, but running into "FIRAuth getUID implementation wasn't set." and I cannot get to my data. I started with a Test app... completely new Firestore project. New iOS project in Swift. New Everything. I just want to read some data. THis is what I have so far...
xCode Version 9.3 (9E145)
FireStore rules
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write;
}
}
}
AppDeligate.swift
import UIKit
import Firebase
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
return true
}
ViewController.swift
import UIKit
import Firebase
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let db = Firestore.firestore()
// this gives
// [Firebase/Core][I-COR000025] FIRAuth getUID implementation wasn't set.
// and I cant read data after ward.
}
NOTE: Add Firebase to your iOS APP.
Step 5...Run your app to verify installation
check_circle Congratulations, you've successfully added Firebase to your app!
So I know the app is connecting properly.
===========================
So I goto the FireStore docs at:
https://firebase.google.com/docs/firestore/quickstart
I add this code to ViewCOntroller.swift .
import UIKit
import Firebase
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let db = Firestore.firestore()
// this gives
// [Firebase/Core][I-COR000025] FIRAuth getUID implementation
wasn't set.
// and I cant read data after ward.
// Add a new document with a generated ID
var ref: DocumentReference? = nil
ref = db.collection("users").addDocument(data: [
"first": "Ada",
"last": "Lovelace",
"born": 1815
]) { err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
}
}
}
And I get this error...
2018-04-30 09:17:34.410768-0400 t5[32887:825090] 4.10.0 -
[Firebase/Core][I-COR000025] FIRAuth getUID implementation wasn't
set.
2018-04-30 09:17:34.625631-0400 t5[32887:825100] TIC Read Status
[1:0x0]: 1:57
2018-04-30 09:17:34.625748-0400 t5[32887:825100] TIC Read Status
[1:0x0]: 1:57
==============================================
Error adding document: Error Domain=FIRFirestoreErrorDomain Code=7
"Missing or insufficient permissions." UserInfo={io.grpc.HeadersKey={
"alt-svc" = "hq=\":443\"; ma=2592000; quic=51303433;
quic=51303432; quic=51303431; quic=51303339;
quic=51303335,quic=\":443\"; ma=2592000; v=\"43,42,41,39,35\"";
"content-disposition" = attachment;
date = "Mon, 30 Apr 2018 13:17:35 GMT";
}, NSLocalizedDescription=Missing or insufficient permissions.,
io.grpc.TrailersKey={
"content-disposition" = attachment;
}}
=========================================
My suspicion is that there is an Auth Issue, but I have my rules set to wide open. I followed instruction perfectly. I get the sence that I have to have some sort of Auth certificate.
That said, ultimately, all I want to do is read data from this site.
So, any thoughts out there what I am doing wrong?
==============================================
I added more Post data and Read Data . and still getting...
`===============================
=====btn READDATA =======
Error getting documents: Error Domain=FIRFirestoreErrorDomain Code=13 "An internal error occurred." UserInfo={NSLocalizedDescription=An internal error occurred.}
2018-04-30 12:01:00.004048-0400 t6[342:28839] Status bar could not find cached time string image. Rendering in-process.
=====btn POSTDATA =======
Error adding document: Error Domain=FIRFirestoreErrorDomain Code=7 "Missing or insufficient permissions." UserInfo={io.grpc.HeadersKey={
"alt-svc" = "hq=\":443\"; ma=2592000; quic=51303433; quic=51303432; quic=51303431; quic=51303339; quic=51303335,quic=\":443\"; ma=2592000; v=\"43,42,41,39,35\"";
"content-disposition" = attachment;
date = "Mon, 30 Apr 2018 16:01:01 GMT";
}, NSLocalizedDescription=Missing or insufficient permissions., io.grpc.TrailersKey={
"content-disposition" = attachment;
}}`
I resolved the issue. My Cocoa Pods needed updating. Actually I did a completely new install of Cocoapds, but I recommend doing a pod update if you have this issue. Simple as that.
yes it was a stupid mistake, but I would like to thank the poster that down gradded me.
Related
I can’t connect to my database. I followed all the steps and I even had to recreate it. Anyone had any similar issues or know how to resolve this?
2023-01-28 14:01:09.944917-0600 Socialcademy[18298:5617783] 10.5.0 - [FirebaseFirestore][I-FST000001] Write at posts/28617F89-5600-4E0B-9963-F52868E00FB9 failed: Missing or insufficient permissions.
[NewPostForm] Cannot create post: Error Domain=FIRFirestoreErrorDomain Code=7 "Missing or insufficient permissions." UserInfo={NSLocalizedDescription=Missing or insufficient permissions.}
These are the other error messages in the console above.
2023-01-28 14:00:55.393987-0600 Socialcademy[18298:5616856] [SceneConfiguration] Info.plist contained no UIScene configuration dictionary (looking for configuration named "(no name)")
2023-01-28 14:00:55.394271-0600 Socialcademy[18298:5616856] [SceneConfiguration] Info.plist contained no UIScene configuration dictionary (looking for configuration named "(no name)")
2023-01-28 14:00:55.397519-0600 Socialcademy[18298:5616856] [SceneConfiguration] Info.plist contained no UIScene configuration dictionary (looking for configuration named "(no name)")
2023-01-28 14:01:00.551653-0600 Socialcademy[18298:5616856] [SceneConfiguration] Info.plist contained no UIScene configuration dictionary (looking for configuration named "(no name)")
2023-01-28 14:01:09.941788-0600 Socialcademy[18298:5617783] 10.5.0 - [FirebaseFirestore][I-FST000001] WriteStream (132d74508) Stream error: 'Permission denied: Missing or insufficient permissions.'
I set up my Firebase database and brought in the right packages onto Xcode. Following all the steps, the Firebase was ready to go. When I ran my app, the error messages popped up, and the database was unresponsive to the action.
I initialized my Firebase:
import SwiftUI
import Firebase
#main
struct SocialcademyApp: App {
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
PostsList()
}
}
}
And I tried to connect to my database:
import Foundation
import FirebaseFirestore
import FirebaseFirestoreSwift
struct PostsRepository {
static let postsReference = Firestore.firestore().collection("posts")
static func create(_ post: Post) async throws {
let document = postsReference.document(post.id.uuidString)
try await document.setData(from: post)
}
}
private extension DocumentReference {
func setData<T: Encodable>(from value: T) async throws {
return try await withCheckedThrowingContinuation { continuation in
try! setData(from: value) { error in
if let error = error {
continuation.resume(throwing: error)
return
}
continuation.resume()
}
}
}
}
Q:
How can permission errors be resolved for Firebase App Check?
Background:
I have enabled App Check per the documents:
DeviceCheck is enabled/configured per:
https://firebase.google.com/docs/app-check/ios/devicecheck-provider
App Attest is enabled configured per:
https://firebase.google.com/docs/app-check/ios/devicecheck-provider
SDK is added to the project, with code from:
https://github.com/firebase/firebase-ios-sdk/blob/master/FirebaseAppCheck/Apps/FIRAppCheckTestApp/FIRAppCheckTestApp/AppDelegate.swift
Specifically, in appdelegate:
Token setup:
FirebaseApp.configure()
requestDeviceCheckToken()
requestDebugToken()
if #available(iOS 14.0, *) {
requestAppAttestToken()
}
calling:
// MARK: App Check providers
func requestDeviceCheckToken() {
guard let firebaseApp = FirebaseApp.app() else {
return
}
DeviceCheckProvider(app: firebaseApp)?.getToken { token, error in
if let token = token {
print("DeviceCheck token: \(token.token), expiration date: \(token.expirationDate)")
}
if let error = error {
print("DeviceCheck error: \((error as NSError).userInfo)")
}
}
}
func requestDebugToken() {
guard let firebaseApp = FirebaseApp.app() else {
return
}
if let debugProvider = AppCheckDebugProvider(app: firebaseApp) {
print("Debug token: \(debugProvider.currentDebugToken())")
debugProvider.getToken { token, error in
if let token = token {
print("Debug FAC token: \(token.token), expiration date: \(token.expirationDate)")
}
if let error = error {
print("Debug error: \(error)")
}
}
}
}
#available(iOS 14.0, *)
func requestAppAttestToken() {
guard let firebaseApp = FirebaseApp.app() else {
return
}
guard let appAttestProvider = AppAttestProvider(app: firebaseApp) else {
print("Failed to instantiate AppAttestProvider")
return
}
appAttestProvider.getToken { token, error in
if let token = token {
print("App Attest FAC token: \(token.token), expiration date: \(token.expirationDate)")
}
if let error = error {
print("App Attest error: \(error)")
}
}
}
requestDeviceCheckToken()returns a permissions error:
DeviceCheck error: ["NSLocalizedFailureReason": The server responded with an error:
- URL: https://firebaseappcheck.googleapis.com/v1beta/projects/<GOOGLE_APP_ID>:exchangeDeviceCheckToken
- HTTP status code: 403
- Response body: {
"error": {
"code": 403,
"message": "Requests from this iOS client application \u003cempty\u003e are blocked.",
"status": "PERMISSION_DENIED",
"details": [
{
"#type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "API_KEY_IOS_APP_BLOCKED",
"domain": "googleapis.com",
"metadata": {
"service": "firebaseappcheck.googleapis.com",
"consumer": "projects/<my project #>"
}
}
]
}
}
requestDebugToken() returns a permissions error:
Debug error: Error Domain=com.firebase.appCheck Code=0 "The server responded with an error:
- URL: https://firebaseappcheck.googleapis.com/v1beta/projects/<GOOGLE_APP_ID>:exchangeDebugToken
- HTTP status code: 403
- Response body: {
"error": {
"code": 403,
"message": "Requests from this iOS client application \u003cempty\u003e are blocked.",
"status": "PERMISSION_DENIED",
"details": [
{
"#type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "API_KEY_IOS_APP_BLOCKED",
"domain": "googleapis.com",
"metadata": {
"consumer": "projects/<my project #>",
"service": "firebaseappcheck.googleapis.com"
}
}
]
}
}
" UserInfo={NSLocalizedFailureReason=The server responded with an error:
- URL: https://firebaseappcheck.googleapis.com/v1beta/projects/<GOOGLE_APP_ID>:exchangeDebugToken
- HTTP status code: 403
- Response body: {
"error": {
"code": 403,
"message": "Requests from this iOS client application \u003cempty\u003e are blocked.",
"status": "PERMISSION_DENIED",
"details": [
{
"#type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "API_KEY_IOS_APP_BLOCKED",
"domain": "googleapis.com",
"metadata": {
"consumer": "projects/<my project #",
"service": "firebaseappcheck.googleapis.com"
}
}
]
}
}
}
requestAppAttestToken() returns an error:
App Attest error: Error Domain=com.firebase.appCheck Code=0 "(null)"
GCP Console does show all calls to the following w/ 100% errors:
google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeDebugToken
google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeDeviceCheckToken
google.firebase.appcheck.v1beta.TokenExchangeService.GenerateAppAttestChallenge
All of which seem to point to a permissions error? Specifically, GOOGLE_APP_ID is in the request URL, but App Check is configured in Firebase via the console...
I'm not seeing anything in the docs or anything obvious in IAM that I missed? :(
Ty in advance for help!
Update
After further testing w/ Postman:
The issue seems to be that the SDK isn't passing the X-Ios-Bundle-Identifier correctly when calling AppCheck API(s).
Steps to get to this conclusion:
From POSTMAN: API call w/ original API_KEY -> yields initial (above) error response/403
From POSTMAN: API call as above, + X-Ios-Bundle-Identifier + valid debug_token -> yields success payload.
So:
any ideas to help ID why the X-Ios-Bundle-Identifier isn't being passed by the SDK? The app is using other Firebase API's w/out issue, so seems limited to the AppCheck SDK...
and/or - can the X-Ios-Bundle-Identifier be programmatically added (in Swift) to the AppCheck calls (it is properly notated in the .plist)
Resolved!
App Check SDK does not currently support the Android / iOS Application Restriction for API keys. With that, you must remove the App Restriction for your API keys to resolve this issue.
Hopefully, the Application Restriction(s) will be supported at some point...
Update!
v8.8.0-beta now supports the bundle ID! :)
1. Configure the private key for DeviceCheck
Make sure you have created a private key for DeviceCheck
And installed it in firebase project settings under AppCheck tab
https://firebase.google.com/docs/app-check/ios/devicecheck-provider
2. Add debug token to firebase.
If you use AppCheckDebugProvider (basically for simulators), after run the project you will see a debug token in the console, you need to copy it and add to AppCheck of the project settings. Than AppCheck will approve it. Also don't forget to add -FIRDebugEnabled for the Arguments Passed on Launch.
https://firebase.google.com/docs/app-check/ios/debug-provider
3. Add production entitlements for AppAttest environment.
The beta version of AppCheck doesn't work with the AppAttest development environment, so you need to setup the production environment in your entitlements. By default, AppAttest works in a development environment, and regardless of your choice in the market it will work with a production.
https://firebase.google.com/docs/app-check/ios/app-attest-provider
https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_developer_devicecheck_appattest-environment
4. Optional:
You can simplify the code
#if targetEnvironment (simulator)
let providerFactory = AppCheckDebugProviderFactory ()
#else
let providerFactory = CustomAppCheckProviderFactory ()
#endif
AppCheck.setAppCheckProviderFactory (providerFactory)
And getting a token
if let fbApp = FirebaseApp.app () {
providerFactory.createProvider(with: fbApp)?.getToken { token, error in
if let token = token {
print ("AppCheck token: \ (token.token), expiration date: \ (token.expirationDate)")
} else if let error = error {
print ("AppCheck error: \ (error as NSError).userInfo)")
}
}
}
Or if you want to protect non-firebase resources, you can get a token like this:
AppCheck.appCheck().token (forcingRefresh: false) { token, error in
if let token = token {
print ("AppCheck token: \ (token.token), expiration date: \ (token.expirationDate)")
} else if let error = error {
print ("AppCheck error: \ (error as NSError).userInfo)")
}
}
https://firebase.google.com/docs/app-check/ios/custom-resource
App Check SDK does not currently support the Android / iOS Application Restriction for API keys. With that, you must remove the App Restriction for your API keys to resolve this issue.
Hopefully, the Application Restriction(s) will be supported at some point...
Got this error - here is what worked for me:
Run app on real Android device
Opened Android Studio → Logcat → search for “DebugAppCheckProvider” → copy the debug secret
In Firebase Go to “App Check” → Apps → 3 dot menu → Manage debug token → Add token → name it → paste the debug secret
Add console log of the token after activation of app check.
try {
await firebase.appCheck().activate("ignored", true);
const token = await getAppCheckToken();
console.log({ token });
} catch (err) {
console.error(err);
}
};
I am running a chat app code , it is giving me the authentication runtime error. Error message is shown below.
I tried several things but nothing worked out yet, if you need another code related information do let me know.
thanks in advance
the code is AppDelegate.Swift file
internal func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
Auth.auth().signInAnonymously { (authUser, error) in
guard Auth.auth().currentUser != nil else {
print(error!)
abort()
}
self.uid = Auth.auth().currentUser!.uid
UserDefaults.standard.set(Auth.auth().currentUser!.uid, forKey: "uid")
let user = User(id: Auth.auth().currentUser!.uid, name: "ぼく")
UserRepository.shared.save(user)
}
return true
}
Error Message
Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={FIRAuthErrorUserInfoNameKey=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information., NSUnderlyingError=0x6000016744b0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 400;
errors = (
{
domain = global;
message = "ADMIN_ONLY_OPERATION";
reason = invalid;
}
);
message = "ADMIN_ONLY_OPERATION";
}}}}
Make sure you have enabled the Anonymous login in your Firebase Console. Take a look at the picture and enable the marked switch. You can find the Firebase Console here.
In addition to Constantin Beer's answer (i'e enabling the anonymous sign in method from firebase), google has enrolled this new beta feature (the identity platform) where you would need to check Enable create (sign up) option. This is mentioned nowhere in the documentation yet, Alex Kozlowski spent a lot of time figuring this out. Please refer the image below
I am getting bit complex issue. I have integrated REST APIs in my existing iOS Swift based Application. It works all correctly.
Now we just changed our domain server so the Base URL of the REST APIs shifted & changed. Now what the issue I am getting is after changing the BaseURL my all POST APIs stopped working.
Note :
I did checked in POSTMan it works correctly
I did tested on Android it works correctly
Even GET APIs with changed BaseURL works correctly on iOS
Only POST APIs not working after changing baseURL
Here is the error message I am getting :
statusCode should be 200, but is 500
response = Optional(<NSHTTPURLResponse: 0x282dfd960> { URL: API_BASE_URL/check_social_id } { Status Code: 500, Headers {
Connection = (
close
);
"Content-Length" = (
289
);
"Content-Type" = (
"text/html; charset=iso-8859-1"
);
Date = (
"Mon, 02 Sep 2019 09:41:13 GMT"
);
Server = (
Apache
);
} })
Note that there is no issue with the API code as its still works with the old BaseURL. Everything with the same code if I just change it to the old BaseURL it works correctly. But If I use new URL it gives the error as I stated above.
New Edit :
After some suggestions I have tried to use the Alamofire library & now I am getting some different error message. Here is my code :
import UIKit
import Alamofire
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "API_URL"
Alamofire.request(urlString, method: .post, parameters: ["media_type": "gmail", "media_id":"12121212121", "fname":"mSolu", "email":"demo.test#gmail.com"],encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
}
}
New error message :
responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end." UserInfo={NSDebugDescription=Garbage at end.}))
Any suggestions or hint will be highly appreciated.
I've installed the Twitter SDK in a project via Fabric.app. I'm able to login to my Twitter account, however when I do anything related to requesting tweets, I threw in these print statements:
print("Failed to load tweets: \(error!.localizedDescription)")
print(error?.localizedFailureReason)
and get this error:
Failed to load tweets: Request failed: forbidden (403)
Optional("Twitter API error : Unable to verify your credentials (code 99)")
but when I add this line to viewDidLoad on my TVC, I return a value:
print("Twitter.sharedInstance().sessionStore.session()?.userID is \(Twitter.sharedInstance().sessionStore.session()?.userID)")
There is a Fabric entry in my Info.plist. I didn't alter or manipulate it from the Fabric.app installation.
In my AppDelegate.swift's didFinishLoadingWithOptions:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// I tried using the consumerKey/consumerSecret for Fabric & Twitter for S's & G's to no avail
Twitter.sharedInstance().startWithConsumerKey("myConsumerKey", consumerSecret: "myConsumerSecret")
Fabric.with([Twitter.self()])
return true
}
I ran thru Fabric's Twitter setup checklist re: setup and I've done everything, yet I've apparently mucked something up. The sample code from Fabric's website doesn't work "out of the box" for me. Any thoughts re: where to look for the problem? I'm out of ideas.
when you request tweets I imagine your code looks like the following, correct?
let client = TWTRAPIClient()
let dataSource = TWTRUserTimelineDataSource(screenName: "fabric", APIClient: client)
Turns out their documentation is incomplete, it should look like
let userID = Twitter.sharedInstance().sessionStore.session()?.userID
let client = TWTRAPIClient(userID: userID)
let dataSource = TWTRUserTimelineDataSource(screenName: "fabric", APIClient: client)
The client object needs your user info to do its thing. I had the same issue.
Another Change ... It's no longer APIClient it's now apiClient
let userID = Twitter.sharedInstance().sessionStore.session()?.userID
let client = TWTRAPIClient(userID: userID)
let dataSource = TWTRUserTimelineDataSource(screenName: "fabric", apiClient: client)