Crashlytics - can't add custom keys, they are not caught on crash - swift

I have a problem with crashlitycs for iOS - I cant set custom keys (they are not registered online).
Everything else is working, I can record the same data in customlogs - that works perfectly, but custom keys doesn't show whatsoever.
Part of the code:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
setCrashlitycsKeys()
}
internal func setCrashlitycsKeys() {
if let userId: Int64 = UserDefaultsHelper.get(for: .UserId) {
Logger.shared.log.warning("User Id: \(userId)")
Crashlytics.sharedInstance().setUserIdentifier(String(describing: userId))
Crashlytics.sharedInstance().setObjectValue(userId, forKey: "userId")
}
if let jsonString: String = UserDefaultsHelper.get(for: .InstanceModuleConfigJson) {
let instancesModuleConfigModel = InstancesModuleConfigModel(JSONString: jsonString)
if let instance = instancesModuleConfigModel?.id {
Crashlytics.sharedInstance().setObjectValue(instance, forKey: "instanceId")
Logger.shared.log.warning("Instance Id: \(instance)")
}
}
}
Logger is just a custom CLSLogv and it works perfectly -
screenshot for log
while theres nothing in keys
screenshot no keys
(it says that no keys found)
Any ideas what can I do or check to make this working? I've spend several hours trying different types of keys, different places and so on but nothings working.
I Use Xdode Version 11.2.1 (11B53),
pod 'Fabric', '~> 1.10.2'
pod 'Crashlytics', '~> 3.14.0'

Ok I found a bug after few hours of searching, in my project I have few targets (mainApp, AppCommon etc) - project is big, so I import smaller functionalities. I had to use Crashlytics pod in 2 of them and that caused an error

Related

[FirebaseAnalytics][I-ACS023001] Deep Link does not contain valid required params issue

[FirebaseAnalytics][I-ACS023001] Deep Link does not contain valid required params. URL params: {
"_cpb" = 1;
"_cpt" = cpit;
"_fpb" = "CIAHEJ4DGgVlbi1JTg==";
"_iumchkactval" = 1;
"_iumenbl" = 1;
"_osl" = "https://helpwise.page.link/TJBU";
"_plt" = 3322;
"_uit" = 1679;
apn = "com.saaslabs.helpwise";
cid = 3913316441535437959;
ibi = "com.saaslabs.helpwise";
isi = 1503985272;
link = "https://app.helpwise.io";
}
VERBOSE: application/scene didBecomeActive
DEBUG: Application Foregrounded started
DEBUG: cancelFocusCall of {
"NOT_ATTRIBUTED" = "<OSUnattributedFocusTimeProcessor: 0x28181f8e0>";
}
I am getting this error how to solve it
I tried the normal integration method from the firebase website but not able to solve this issue
This error happens if your link structure is not properly configured. You have to make sure that your link parameter is URL encoded.
After trying lots of methods I was final able to solve the issue.
The mistake that I made was in the app delegate I had overridden the function which intercepts those links in iOS due to which it was not able to get some information that was required commenting that line solved the issue.
those lines were:
override func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: #escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
print("app delegate=====\(userActivity.webpageURL?.absoluteString ?? "NO WEBPAGE URL")")
return true }

didReceiveRemoteNotification not being called on MacCatalyst

When I create a CKSubscription, didReceiveRemoteNotification gets called on iOS just fine but not on MacOS. I came across a 2015 SO thread talking about a bug and the suggested workaround was to set the notification info's soundName to an empty string - unfortunately that didn't resolve the issue for me.
Here is how I register my remote notifications:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let subscription = CKQuerySubscription(recordType: "Reminder", predicate: NSPredicate(format: "TRUEPREDICATE"), options: [.firesOnRecordCreation, .firesOnRecordUpdate])
// Here we customize the notification message
let info = CKSubscription.NotificationInfo()
info.shouldSendContentAvailable = true
info.desiredKeys = ["identifier", "title", "date"]
info.soundName = ""
subscription.notificationInfo = info
// Save the subscription to Private Database in Cloudkit
CKContainer.default().privateCloudDatabase.save(subscription, completionHandler: { subscription, error in
if error == nil {
// Subscription saved successfully
} else {
// Error occurred
}
})
}
This has to do with the bundle identifier being different on Mac Catalyst. Thanks to the soon to be introduced universal app purchase, catalyst apps can now bear the same bundle identifier as their iOS counterpart, and that fixes the issue.
Note that I was also experiencing issues with cloudkit key values not syncing on Mac (NSUbiquitousKeyValueStore). Having a single bundle id for Mac and iOS fixed the problem too.

How to authenicate AWS Appsync in iOS (Swift)

Junior developer here.
I'm trying to get AWS Appsync to work in an iOS app I'm currently building, but I cant get authentication working.
I want to replicate this Javascript code in swift, for my authenication.
Amplify.configure({
Auth: {
region: "<REGION>",
userPoolId: "<USER-POOL-ID>",
userPoolWebClientId: "<USER-POOL-WEB-CLIENT-ID>"
}
});
const client = new AWSAppSyncClient({
auth: {
jwtToken: async () =>
(await Auth.currentSession()).getIdToken().getJwtToken(),
type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS
},
disableOffline: true,
region: "<REGION>",
url:
"<ENDPOINT-URL>"
});
I have found a similar problem here:
cannot authenticate user for aws appsync with swift SDK
But he hasn't gotten an answer.
I have googled plenty but cant seem to find a solution.
Could one of you kind programer souls point me in the right direction?
AWS SDK for iOS - AppSync solves your use-case. You can check out the documentation here: https://docs.aws.amazon.com/appsync/latest/devguide/building-a-client-app-ios.html. You can check out the source code here: https://github.com/awslabs/aws-mobile-appsync-sdk-ios. There is a starter app which will help you onboard quickly: https://github.com/aws-samples/aws-mobile-appsync-events-starter-ios.
import UIKit
import AWSAppSync
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var appSyncClient: AWSAppSyncClient?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Set up Amazon Cognito credentials
let credentialsProvider = AWSCognitoCredentialsProvider(regionType: CognitoIdentityRegion,
identityPoolId: CognitoIdentityPoolId)
// You can choose your database location, accessible by the SDK
let databaseURL = URL(fileURLWithPath:NSTemporaryDirectory()).appendingPathComponent(database_name)
do {
// Initialize the AWS AppSync configuration
let appSyncConfig = try AWSAppSyncClientConfiguration(url: AppSyncEndpointURL,
serviceRegion: AppSyncRegion,
credentialsProvider: credentialsProvider,
databaseURL:databaseURL)
// Initialize the AWS AppSync client
appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncConfig)
// Set id as the cache key for objects
appSyncClient?.apolloClient?.cacheKeyForObject = { $0["id"] }
} catch {
print("Error initializing appsync client. \(error)")
}
return true
}
// ... other intercept methods
}

Determine login type using AWS Cognito during resume session (Swift)

I'm having a hard time trying to figure out how to determine the login type during a resume session using AWS Cognito. My code is based upon the MobileHub sample (below).
I've integrated a name/password mode for user pools (account creation and login) as well as as a Facebook login button which all works perfectly.
I have some logic in my application that needs to behave differently depending on the login type but I can't figure out how to do it.
Anyone done this?
func didFinishLaunching(_ application: UIApplication, withOptions launchOptions: [AnyHashable: Any]?) -> Bool {
print("didFinishLaunching:")
// Register the sign in provider instances with their unique identifier
AWSSignInManager.sharedInstance().register(signInProvider: AWSFacebookSignInProvider.sharedInstance())
AWSIdentityProfileManager.sharedInstance().register(FacebookIdentityProfile.sharedInstance(), forProviderKey: AWSFacebookSignInProvider.sharedInstance().identityProviderName)
AWSSignInManager.sharedInstance().register(signInProvider: AWSCognitoUserPoolsSignInProvider.sharedInstance())
AWSIdentityProfileManager.sharedInstance().register(UserPoolsIdentityProfile.sharedInstance(), forProviderKey: AWSCognitoUserPoolsSignInProvider.sharedInstance().identityProviderName)
setupAPIGateway()
setupS3()
let didFinishLaunching: Bool = AWSSignInManager.sharedInstance().interceptApplication(application, didFinishLaunchingWithOptions: launchOptions)
if (!isInitialized) {
AWSSignInManager.sharedInstance().resumeSession(completionHandler: { (result: Any?, authState: AWSIdentityManagerAuthState, error: Error?) in
print("didFinishLaunching Result: \(String(describing: result)) AuthState: \(authState) \n Error:\(String(describing: error))")
if authState == .authenticated {
// Facebook or Cognito???
AWSCognitoUserAuthHelper.getCurrentUserAttribute(name: "sub", completionHandler: { (userid) in
// we need to fetch the user
ObjectManager.instance.getUser(userid: userid, completionHandler: { (user) in
ObjectManager.instance.setCurrentUser(user: user)
})
})
}
}) // If you get an EXC_BAD_ACCESS here in iOS Simulator, then do Simulator -> "Reset Content and Settings..."
// This will clear bad auth tokens stored by other apps with the same bundle ID.
isInitialized = true
}
return didFinishLaunching
}
One solution I found was to cast to the different identity profile types such as the following:
let identityManager = AWSIdentityManager.default()
if let fbIdentityProfile = identityManager.identityProfile as? FacebookIdentityProfile {
print("didFinishLaunching - Facebook login")
} else if let upIdentityProfile = identityManager.identityProfile as? UserPoolsIdentityProfile {
print("didFinishLaunching - User Pools login")
}
I can model logic in my application around this. Not sure if there is a cleaner approach using the MobileHub helper classes or AWS APIs but this works.

firebase token is null and token refresh is called continously in my testFlight

First of all, i have no problem for FCM, firebase token is never null every time tokenRefreshNotification is called. But after, i add Google analytics, i got weird problem for Firebase token. Every time i turn off and turn on notification in my app settings used
UIApplication.shared.registerForRemoteNotifications()
my tokenRefreshNotification is called continously and it doesn't stop looping until i force close my apps. At first, my app crash, and when i try to trace it with NsLog, i found that Firebase token is null. The problem occurs only when i`m using my apps installed from TestFlight / production. When i try it from my Xcode builder, firebase token is null only once, but the second call, firebase token is exist and it stop working.
For google Analytics, it works fine and in my GoogleService-info.plist,
i have set IS_ANALYTICS_ENABLED to YES and IS_GCM_ENABLED to YES also. For the other, IS_ADS_ENABLED = YES, IS_APPINVITE_ENABLED = NO, and IS_SIGNIN_ENABLED = YES
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FIRApp.configure()
NotificationCenter.default.addObserver(self, selector: #selector(self.registerNotification), name: NSNotification.Name(rawValue: "registerNotification"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification(_:)), name: .firInstanceIDTokenRefresh, object: nil)
setupGoogleAnalytics()
return true
}
//when firebase token is null, this function is working continously until my firebase token is exist
func tokenRefreshNotification(_ notification: Notification) {
print("token Refresh")
if FIRInstanceID.instanceID().token() == nil{
NSLog("firebase token is null")
}
if (UserDefaults.standard.object(forKey: "id") != nil) && FIRInstanceID.instanceID().token() != nil{
FIRInstanceID.instanceID().getWithHandler({ (instanceID, error) in
NSLog("instanceID: \(instanceID!)")
//save firebase token to my database, sorry i can`t show it
})
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
Note: At the first launch, i called my RegisterForRemoteNotifications, at TestFlight version, when tokenRefreshNotification is called, the firebase token is null, but the second call, firebase token is exist, so it could stop. But, when i run my app from Xcode, the first call is success because firebase token is not null.
i have figured it out! just change ANPS Type token from Sandbox to Unknown!
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// With swizzling disabled you must set the APNs token here.
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.unknown)
}