Get Firebase database from another firebase app - ios

How to access firebase database from another firebase app in swift5?
We have two apps in one account one is driver app and rider app.
I am storing data in driver real time database and want to access that database in rider app.
Let me know if anyone have this solution.

To access the same database from two iOS application, you simply create two apps in the Firebase console of that project. This will give you a GoogleService-Info.plist file with information about both apps, and each app will pick its configuration from there based on the iOS bundle ID.
Also see step 2 of register your app in the Firebase setup instructions for iOS developers.
After this both apps can access the same database, as well as all other services.

Here is code to use multiple firebase database in a single iOS app
func initDatabase() {
FIRDatabase().database() // gets you the default database
let options = FIROptions(googleAppID: bundleID: , GCMSenderID: , APIKey: , clientID: , trackingID: , androidClientID: , databaseURL: "https://othernamespace.firebaseio.com", storageBucket: , deepLinkURLScheme: ) // fill in all the other fields
FIRApp.configureWithName("anotherClient", options: options)
let app = FIRApp(named: "anotherClient")
FIRDatabase.database(app: app!) // gets you the named other database
}
Or you can initialize from another named plist rather than a huge constructor:
let filePath = NSBundle.mainBundle().pathForResource("Second-GoogleService-Info", ofType:"plist")
let options = FIROptions(contentsOfFile:filePath)

Related

How ios app data connect to azure sql database?

I am new xcode and swift lanuage, I am making a ios application with xcode, it is a qr code genrator and I want to make qr code data sync to azure sql database, but I don't know how to write the function to sync data to azure sql database. How should I write the function to sync the result of qrcode generator to azure sql database?
Here is my qr code generator Code:
func Generate(id:string)-> UIImage {
let com = id.data(using: .utf8)
filter.setValue(com, forKey: "inputMessage")
if let qr = filter.outputImage {
if let qrImage = cont.createCGImage(qr, from: qr.extent){
return UIImage(cgImage: qrImage)
}
}
return UIImage(systemName: "xmark") ?? UIImage()
}
how could i sync the result data to azure sql database? do any experts know how to write the function?
To connect with IOS app first you need to create mobile app in azure portal.
for that you can follow below procedure:
Go to search bar in azure portal and search for app service click on that and create new by giving required details:
Click on create, after deployment go to configuration under settings and click on new application settings. In the Add/Edit application setting page, enter Name as MobileAppsManagement_EXTENSION_VERSION and Value as latest and hit OK.
for creating database connection Download the client SDK quickstarts for the following platforms:
iOS (Objective-C)
iOS (Swift)
Android (Java)
Xamarin.iOS
Xamarin.Android
Xamarin.Forms
Cordova
Windows (C#)
Create Azure sql database and copy the connection string of database:
Server=tcp:<server>.database.windows.net,1433;Initial Catalog=<db>;Persist Security Info=False;User ID=demouser;Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
Add the connection string to your mobile app In App Service, you can manage connection strings for your application by using the Configuration option in the menu.
To add a connection string:
Click on the Application settings tab.
Click on [+] New connection string.
You will need to provide Name, Value and Type for your connection string.
Type Name as MS_TableConnectionString
Value should be the connecting string you formed in the step before.
If you are adding a connection string to a SQL Azure database choose SQLAzure under type.
In this way you can connect azure SQL database to IOS app.
for more clarification you can refere
1.Create an iOS app - Azure Mobile Apps | Microsoft Learn
2.https://social.msdn.microsoft.com/Forums/en-US/f50195df-0fab-4361-82ac-e75a338b69cc/connect-to-azure-sql-database-from-ios-app-written-in-swift

iOS: Firebase: Database lives in a different region. Where to put the link?

I am new to SwiftUI and I am currently making my first ever Firebase app. (Xcode SwiftUI iOS 15.0)
I have this problem. When I want to save messages to my Realtime Database, I get this error:
Firebase Database connection was forcefully killed by the server.
Will not attempt reconnect. Reason: Database lives in a different
region. Please change your database URL to
"My Firebase URL"
(My database is already linked to this URL)
On other posts I saw this soloution:
let ref = Database.database(url: "My Firebase URL")
Where do I have to put this line of code?
Thank you!
You have to put that code wherever you are creating a reference to data from Firebase.
If you look at this code from step 3 of the Firebase documentation on setting up a connection to the database:
var ref: DatabaseReference!
ref = Database.database().reference()
This syntax creates a reference to the database as it is defined in your GoogleService-Info.plist file.
Since you want to specify the URL in your code, you'd do:
var ref: DatabaseReference!
ref = Database.database("your database URL").reference()
And then use ref everywhere else to read and write data.
You can alternatively also download an updated GoogleService-Info.plist file from the Firebase console, and replace the one in your Xcode project with it. In that case the SDK will pick up the URL from the updated file.

Where is the UserDefaults data stored when sharing it with app and extension?

I have created an application which uses "UserDefaults" for storing the data. I am using the App Groups capability to share the data between the host app and extension. Where can I see the data stored in it?
When using the default (UserDefaults.standard) UserDefaults I am able to see the data stored under "Library -> Preferences -> appbundlename.plist.
The application is displaying the data even when I kill it from background.(data is persisting)
let sharedDefaults = UserDefaults(suiteName: ListManager.GroupId)
let groupPath = FileManager().containerURL(forSecurityApplicationGroupIdentifier: ListManager.GroupId)!.appendingPathComponent("Library/Preferences")
Will get you the path to the shared group defaults.
Just be sure to enable the App Groups capabilities for your app (and extensions). Otherwise, your group defaults will just appear in the same directory as the standard user defaults (and thus persisting between launches) but will be inaccessible by your other apps or extensions.

HKHealthStore request authorization once again

In the previous version of my iOS app I was asking users to grant access to write Dietary Energy in Health app (see the code bellow):
let typesToWrite: Set<HKSampleType> = [HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryEnergyConsumed)!]
healthStore.requestAuthorization(toShare: typesToWrite , read: nil) { (success, error) in
//...
}
And many users gave access to write Energy Data to Health app.
Now, I want to make an update for my app, and I need to add another sample type: Dietary Sugar, and I would like to show again the Health access window, in order to old users gave access to the Dietary Sugar too. The problem is that this window is not showing anymore for old users. How can I force a request authorization for new added type in update version of the app? Thank you.

Communicating and persisting data between apps with App Groups

iOS 8 revealed a new API yesterday concerning App Groups. It was kind of messy before to share data and communicate between apps and I believe that's precisely what App Groups is intended to correct.
In my app I have enabled App Groups and added a new group but I just can't find any documentation on how to use it. Documentation and API references only state how to add a group.
So what is App Groups really intended to do? Is there any documentation somewhere on how to use it?
Another benefit to App Groups is the ability to share a NSUserDefaults database. This also works for App Extensions (notification center widgets, custom keyboards, etc).
Initialize your NSUserDefaults object like this in all applications in the app group and they will share the database:
Objective-C:
[[NSUserDefaults alloc] initWithSuiteName:#"<group identifier>"];
Swift:
NSUserDefaults(suiteName: "<group identifier>")
Keep in mind everything from the [NSUserDefaults standardUserDefaults] database for each application will not carry over into this database.
The documentation gives a correct example as well (As of Beta 3).
And don't forget to synchronize the database:
[yourDefaults synchronize];
Sharing NSUserDefaults data between multiple apps
In order to have shared defaults between an app and an extension or between 2 apps you have to add an App Group in your settings using the following steps:
In the Project Navigator click on the *.xcodeproj file (should be at the top).
To the right of the Project Navigator look for Project and Targets. Under targets click on your primary target (should be the first thing under Targets).
Towards the top, click on the Capabilities tab.
In the App Groups section click the switch to the right to turn App Groups ON.
Click on the + button and add an App Group named group.com.company.myApp.
Go to the same place in your other apps and this group should now be available to select. Turn this group on for each app that will be using this shared data.
Note: If you go to the Apple Developer Portal (the Apple website that shows all of your Certificates, Identifiers, Devices and Provisioning Profiles) and go to Identifiers > App Groups you should see this new App Group.
To store data:
var userDefaults = NSUserDefaults(suiteName: "group.com.company.myApp")!
userDefaults.setObject("user12345", forKey: "userId")
userDefaults.synchronize()
To retrieve data:
var userDefaults = NSUserDefaults(suiteName: "group.com.company.myApp")
if let testUserId = userDefaults?.objectForKey("userId") as? String {
print("User Id: \(testUserId)")
}
Application groups, according to my interpretation of the existing documentation, are primarily targeted for extensions, more specifically, for widgets. Widgets are their own application bundle that coexist with your app. Since they are a separate application and therefore have their own sandbox, you will need to use App Groups to share files.
After some header grep'ing, I think I found the API needed, but was actually put in as part of iOS 7.
NSFileManager has a method on it containerURLForSecurityApplicationGroupIdentifier: where you can pass in the identifier you created when turning on App Groups for your apps:
NSURL *containerURL = [[NSFileManager defaultManager]
containerURLForSecurityApplicationGroupIdentifier:#"group.com.company.app"];
One important trap I tapped into today is the following:
In many projects I saw a single app target and with different bundle identifiers set for each configuration of that target. Here things get messy. What the developers intended was to create a debug app for the debug config and a production app for the release target.
If you do so both apps will share the same NSUserDefaults when they are set up like so
var userDefaults = NSUserDefaults(suiteName: "group.com.company.myApp")
userDefaults!.setObject("user12345", forKey: "userId")
userDefaults!.synchronize()
This causes problems in many places:
Imagine you set YES for a key when a special app-intro-screen has been shown to the user. The other app will now also read YES and don't show the intro.
Yes some apps also store oAuth tokens in their user defaults. Anyways... Depending on the implementation, the app will recognize that there's a token and start retrieving data using the wrong token. The chance is high that this will fail with strange errors.
The solution to this problem in general is to prefix the defaults keys with the current configuration built. You can detect the configuration easily at runtime by setting different bundle identifiers for your configurations. Then just read the bundle identifier from NSBundle.mainBundle(). If you have the same bundle identifiers you need to set different preprocessor macros like
#ifdef DEBUG
NSString* configuration = #"debug";
#elif RELEASE
NSString* configuration = #"release";
#endif
In Swift it will look almost the same:
#if DEBUG
let configuration = "debug"
#elseif RELEASE
let configuration = "release"
#endif
iOS App Group
App Group allows you to share data(UserDefaults, Files, CoreData(manage model graph), POSIX locks) between different processes(applications, extensions...) from the same development team(account). It creates a shared container whit id which shoyld start from group. for saving/caching data which you are allowed to access thought url and IPC
To use App Group with UserDefaults
Add App Group capability with the same id for ALL targets(app, extension...) which you will get an access from
After creation you are able to check it on Apple Developer. Certificates, IDs & Profiles -> Identifiers -> ALL Groups
Write from Application1
let defaults = UserDefaults(suiteName: "group.goforit")
defaults?.setValue("Hello World!", forKey: "key1")
Read from Application2
let defaults = UserDefaults(suiteName: "group.goforit")
let result = defaults?.value(forKey: "key1") //Hello World!
shared container root location single URL.
let rootURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.goforit")
//file:///Users/alex/Library/Developer/CoreSimulator/Devices/1AF41817-FE2E-485A-A592-12C39C0B0141/data/Containers/Shared/AppGroup/DC14D43F-2C2C-4771-83BE-64A9F54BD2E1/
[iOS App Extension]
To store
let shared: NSUserDefaults = NSUserDefaults(suiteName: "group.abcapp")!
shared.setObject("abc.png", forKey: "favEmoji")
shared.synchronize()

Resources