Quantcast
Channel: Active questions tagged react-native+ios - Stack Overflow
Viewing all 17237 articles
Browse latest View live

react-native on iOS17, Exception thrown while executing UI block: 'parentNode' is a required parameter

$
0
0

I am running my react native app on an iOS device, my UI elements are not rendered unless i reload the appI have tried rending other elements, removing elements one by one, it's not clear to me what exactly is causing the issue

The production release of the app seems to be working fine on all iOS devices, i have gone through removing and re-installing pods and node packages, reordering the build phases (in regards to including frameworks and libraries) more than once, unfortunately i can't remember the difference regarding all these details

It's a legacy app and i am not familiar with all the stack / components but i know enough, i am just not sure what am i looking for to solve this issue

I only get this error on iOS 17.0 and any release that came after (as of today iOS 17.1)

The error message:

Exception thrown while executing UI block: 'parentNode' is a required parameter__44-[RCTUIManager flushUIBlocksWithCompletion:]_block_invoke  RCTUIManager.m:1201__44-[RCTUIManager flushUIBlocksWithCompletion:]_block_invoke.206__RCTExecuteOnMainQueue_block_invoke149FF9CD-3E92-321D-B92F-EF58717C70B6149FF9CD-3E92-321D-B92F-EF58717C70B6149FF9CD-3E92-321D-B92F-EF58717C70B6_dispatch_main_queue_callback_4CFCEB74A0C-5EA4-3F5A-9DE8-73F0DAD2F4CBCEB74A0C-5EA4-3F5A-9DE8-73F0DAD2F4CBCFRunLoopRunSpecificGSEventRunModalEC1206D7-B4C9-3257-BB63-08E26A802416UIApplicationMainmain0D856E72-9A63-3B5B-879F-8D026115A4F0

react-native info

System:    OS: macOS 14.0    CPU: (8) arm64 Apple M1    Memory: 42.08 MB / 16.00 GB    Shell: 5.9 - /bin/zsh  Binaries:    Node: 16.6.1 - ~/.nvm/versions/node/v16.6.1/bin/node    Yarn: 1.22.19 - /opt/homebrew/bin/yarn    npm: 7.20.3 - ~/.nvm/versions/node/v16.6.1/bin/npm    Watchman: 2023.09.04.00 - /opt/homebrew/bin/watchman  Managers:    CocoaPods: 1.11.3 - /usr/local/bin/pod  SDKs:    iOS SDK:      Platforms: DriverKit 23.0, iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0    Android SDK: Not Found  IDEs:    Android Studio: 2021.3 AI-213.7172.25.2113.9014738    Xcode: 15.0.1/15A507 - /usr/bin/xcodebuild  Languages:    Java: 11.0.17 - /usr/bin/javac  npmPackages:    @react-native-community/cli: Not Found    react: 17.0.2 => 17.0.2     react-native: 0.68.2 => 0.68.2     react-native-macos: Not Found  npmGlobalPackages:    *react-native*: Not Found

I wonder if any one is facing this issue with iOS 17. if i should hold off spending a lot of time of investigating this (on a strict timeline) due to the fresh release of iOS 17, but i don't have / can't have userbase information in that regard


Deeplinking not navigating to expected location if app is removed from memory in swift iOS

$
0
0

I am new to ReactNative.In my current app, deeplinking was coded and working well when it was done through appDelegate.later, the app support Carplay as well, so to handle multiple scenes sceneDelegate was introduced.

After that, whenever deeplinking is invoked then

  • if the app is in background state then it launches the app at specific location
  • if the app is removed from memory and deeplink clicked then it only launches the app, but doesn't navigate to desired screen.

What is the issue here,what things I need to change / add to make app launch at desired location even if app is removed from memory.

Here is my appDelegate.

func appDelegate() -> AppDelegate {    return UIApplication.shared.delegate as! AppDelegate}@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate {  var window: UIWindow?  var appCenter: AppCenterReactNative!  var appCenterAnaltics: AppCenterReactNativeAnalytics!  var appCenterCrashes: AppCenterReactNativeCrashes!  let mParticleKey: String = ReactNativeConfig.env(for: "MPARTICLE_IOS_KEY");  let mParticleSecret: String = ReactNativeConfig.env(for: "MPARTICLE_IOS_SECRET");  // var mParticleEmail: String = ReactNativeConfig.env(for: "MPARTICLE_EMAIL");  let mParticleEnv: String = ReactNativeConfig.env(for: "MPARTICLE_ENV");  let mParticleDataPlanName: String = ReactNativeConfig.env(for: "MPARTICLE_DATAPLAN");  let mParticleDataPlanVersion: String = ReactNativeConfig.env(for: "MPARTICLE_DATAPLAN_VERSION");  let moEngageAppID: String = ReactNativeConfig.env(for: "MOENGAGE_APP_ID");  /* CarPlay setup */  var playableContentManager: MPPlayableContentManager?  var remoteCommandCenter: MPRemoteCommandCenter?  let carplayPlaylist = CarPlayPlaylist()  let carplayArtworkCache = NSCache<AnyObject, UIImage>()  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {    initializeFlipper(with: application)    /* Moengage */    let sdkConfig = MoEngageSDKConfig(appId: moEngageAppID, dataCenter: .data_center_01);    MoEngageInitializer.sharedInstance().initializeDefaultSDKConfig(sdkConfig, andLaunchOptions: launchOptions ?? [:])    AppCenterReactNative.register()    AppCenterReactNativeAnalytics.register(withInitiallyEnabled: true);    AppCenterReactNativeCrashes.registerWithAutomaticProcessing();    FirebaseApp.configure()    /* ChromeCast activate */    let receiverAppID:String = "CC1AD845"; // or @"ABCD1234"    let criteria = GCKDiscoveryCriteria(applicationID: receiverAppID)    let options = GCKCastOptions(discoveryCriteria: criteria)    GCKCastContext.setSharedInstanceWith(options)    let bridge = RCTBridge(delegate: self, launchOptions: launchOptions)!    let rootView = RCTRootView(bridge: bridge, moduleName: "nova", initialProperties: nil)    let rootViewController = UIViewController()    rootViewController.view = rootView    self.window = UIWindow(frame: UIScreen.main.bounds)    self.window?.rootViewController = rootViewController    self.window?.makeKeyAndVisible()    /* MPNowPlayingInfoCenter */    UIApplication.shared.beginReceivingRemoteControlEvents()    setupCarPlay();    RNSplashScreen.show()    /* Setup MParticle */    var dPlanVersion:NSNumber = 0    if let versionInt = Int(mParticleDataPlanVersion) {     dPlanVersion = NSNumber(value:versionInt)    }    var mParticleEnvMode: MPEnvironment = MPEnvironment.development    if(mParticleEnv == "PROD") {      mParticleEnvMode =  MPEnvironment.production    }    let mParticleOptions = MParticleOptions(key: mParticleKey, secret: mParticleSecret)    mParticleOptions.environment = mParticleEnvMode    mParticleOptions.dataPlanId = mParticleDataPlanName    mParticleOptions.dataPlanVersion = dPlanVersion    mParticleOptions.proxyAppDelegate = false    if #available(iOS 14, *) {       mParticleOptions.attStatus = NSNumber.init(value: ATTrackingManager.trackingAuthorizationStatus.rawValue)    }    // Remove AST Events    mParticleOptions.onCreateBatch = { (batch: [AnyHashable: Any]) -> [AnyHashable: Any]? in        var modifiedBatch = batch        guard var modifiedMessages = batch["msgs"] as? [AnyHashable] else { return batch }        var index = 0        for message in modifiedMessages {            // the following removes Application State Transition (AST) events, except for those uploaded on installs and upgrades            // Install AST events are used by many server-side integrations and are used by            // mParticle to ensure there is a user profile created            guard let messageAsDictionary = message as? [AnyHashable: Any] else { continue }            guard let type = messageAsDictionary["dt"] as? String else { continue }            let isFirstRun = messageAsDictionary["ifr"] as? Bool ?? false            let isUpgrade = messageAsDictionary["iu"] as? Bool ?? false            if type == "ast" && !isFirstRun && !isUpgrade {                modifiedMessages.remove(at: index)                index -= 1            }            index += 1        }        modifiedBatch["msgs"] = modifiedMessages        return modifiedBatch    }    // Start the SDK    MParticle.sharedInstance().start(with: mParticleOptions)    return true  }   private func initializeFlipper(with application: UIApplication) {    #if DEBUG      let client = FlipperClient.shared()      let layoutDescriptorMapper = SKDescriptorMapper(defaults: ())      client?.add(FlipperKitLayoutPlugin(rootNode: application, with: layoutDescriptorMapper!))      client?.add(FKUserDefaultsPlugin(suiteName: "nova"))      client?.add(FlipperKitReactPlugin())      client?.add(FlipperKitNetworkPlugin(networkAdapter: SKIOSNetworkAdapter()))      client?.start()    #endif  }  /* Allow for orientation change */  func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {    return Orientation.getOrientation()  }  /* Allow Link back URLs ('nova://') */  public func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {    return RCTLinkingManager.application(app, open: url, options: options)  }  public func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {    return RCTLinkingManager.application(application, continue: userActivity, restorationHandler: restorationHandler)  }}extension AppDelegate: RCTBridgeDelegate {    func sourceURL(for bridge: RCTBridge!) -> URL! {        #if DEBUG        return RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")        #else        return CodePush.bundleURL()        #endif    }}

This is my sceneDelegate

@available(iOS 13.0, *)class SceneDelegate: UIResponder, UIWindowSceneDelegate, RCTBridgeDelegate {  let mParticleKey: String = ReactNativeConfig.env(for: "MPARTICLE_IOS_KEY");  let mParticleSecret: String = ReactNativeConfig.env(for: "MPARTICLE_IOS_SECRET");  // var mParticleEmail: String = ReactNativeConfig.env(for: "MPARTICLE_EMAIL");  let mParticleEnv: String = ReactNativeConfig.env(for: "MPARTICLE_ENV");  let mParticleDataPlanName: String = ReactNativeConfig.env(for: "MPARTICLE_DATAPLAN");  let mParticleDataPlanVersion: String = ReactNativeConfig.env(for: "MPARTICLE_DATAPLAN_VERSION");  func sourceURL(for bridge: RCTBridge!) -> URL! {    let jsCodeLocation: URL    jsCodeLocation = RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")    return jsCodeLocation  }  var window: UIWindow?  func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {    var deeplink: URL?    if let userActivity = connectionOptions.userActivities.first(where: { $0.activityType == NSUserActivityTypeBrowsingWeb }),        let webpageURL = userActivity.webpageURL {        // get universal link        deeplink = webpageURL    } else if let urlContext = connectionOptions.urlContexts.first {        // get app scheme deep link        deeplink = urlContext.url    }    handleDeepLink(deeplink)    let bridge = RCTBridge.init(delegate: self, launchOptions: nil)    let rootView = RCTRootView.init(bridge: bridge!, moduleName: "nova", initialProperties: nil)    let rootViewController = UIViewController()    rootViewController.view = rootView    AppCenterReactNative.register()    AppCenterReactNativeAnalytics.register(withInitiallyEnabled: true);    AppCenterReactNativeCrashes.registerWithAutomaticProcessing();    FirebaseApp.configure()    /* ChromeCast activate */    let receiverAppID:String = "CC1AD845"; // or @"ABCD1234"    let criteria = GCKDiscoveryCriteria(applicationID: receiverAppID)    let options = GCKCastOptions(discoveryCriteria: criteria)    GCKCastContext.setSharedInstanceWith(options)    /* MPNowPlayingInfoCenter */    UIApplication.shared.beginReceivingRemoteControlEvents()    RNSplashScreen.show()    // Instantiate root view here instead of scene to start the bundler on app launch    RNBridgeInstanceHolder.sharedInstance.bridge = bridge    RNBridgeInstanceHolder.sharedInstance.rctRootView = rootView    if let windowScene = scene as? UIWindowScene {       let window = UIWindow(windowScene: windowScene)      window.rootViewController = rootViewController       self.window = window       window.makeKeyAndVisible()    }    if #unavailable(iOS 14.0) {      appDelegate().setupCarPlay()    }    /* Setup MParticle */    var dPlanVersion:NSNumber = 0    if let versionInt = Int(mParticleDataPlanVersion) {     dPlanVersion = NSNumber(value:versionInt)    }    var mParticleEnvMode: MPEnvironment = MPEnvironment.development    if(mParticleEnv == "PROD") {      mParticleEnvMode =  MPEnvironment.production    }    let mParticleOptions = MParticleOptions(key: mParticleKey, secret: mParticleSecret)    mParticleOptions.environment = mParticleEnvMode    mParticleOptions.dataPlanId = mParticleDataPlanName    mParticleOptions.dataPlanVersion = dPlanVersion    mParticleOptions.proxyAppDelegate = false    if #available(iOS 14, *) {       mParticleOptions.attStatus = NSNumber.init(value: ATTrackingManager.trackingAuthorizationStatus.rawValue)    }    // Remove AST Events    mParticleOptions.onCreateBatch = { (batch: [AnyHashable: Any]) -> [AnyHashable: Any]? in        var modifiedBatch = batch        guard var modifiedMessages = batch["msgs"] as? [AnyHashable] else { return batch }        var index = 0        for message in modifiedMessages {            // the following removes Application State Transition (AST) events, except for those uploaded on installs and upgrades            // Install AST events are used by many server-side integrations and are used by            // mParticle to ensure there is a user profile created            guard let messageAsDictionary = message as? [AnyHashable: Any] else { continue }            guard let type = messageAsDictionary["dt"] as? String else { continue }            let isFirstRun = messageAsDictionary["ifr"] as? Bool ?? false            let isUpgrade = messageAsDictionary["iu"] as? Bool ?? false            if type == "ast" && !isFirstRun && !isUpgrade {                modifiedMessages.remove(at: index)                index -= 1            }            index += 1        }        modifiedBatch["msgs"] = modifiedMessages        return modifiedBatch    }    // Start the SDK    MParticle.sharedInstance().start(with: mParticleOptions)  }  //handels app scheme novaplayer:// in active and inactive foreground mode  func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {      if let url = URLContexts.first?.url {        handleDeepLink(url)      }  }  //handels universal links https://novaplayer in active and inactive foreground mode  func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {    if userActivity.activityType == NSUserActivityTypeBrowsingWeb {    if let url = userActivity.webpageURL {                       handleDeepLink(url)      }    }  }  //function to pass deelink value to react native  func handleDeepLink(_ deeplink: URL?) {      guard let deeplink = deeplink else {          os_log("No deeplink found", log: OSLog.default, type: .debug)          return      }      os_log("Deeplink URL FOUND: %@", log: OSLog.default, type: .debug, deeplink.absoluteString)      RCTLinkingManager.application(UIApplication.shared, open: deeplink, options: [:])  }}

Here is my info.plist piece of code.

<key>UIApplicationSceneManifest</key><dict><key>UISceneConfigurations</key><dict><key>CPTemplateApplicationSceneSessionRoleApplication</key><array><dict><key>UISceneClassName</key><string>CPTemplateApplicationScene</string><key>UISceneConfigurationName</key><string>CarPlay Configuration</string><key>UISceneDelegateClassName</key><string>$(PRODUCT_MODULE_NAME).CarPlaySceneDelegate</string></dict></array><key>UIWindowSceneSessionRoleApplication</key><array><dict><key>UISceneConfigurationName</key><string>Default Configuration</string><key>UISceneDelegateClassName</key><string>$(PRODUCT_MODULE_NAME).SceneDelegate</string></dict></array></dict></dict>

It is working as expected in Android build, but having issue only with iOS build.If I switch back to appDelegate without scenedelegate then my Carplay app is not getting launched.

Any help will be appreciated.

Thanks.

Need guidance on creating a custom npm package with native module configuration for React Native

$
0
0

I have been developing a React Native application and I am looking for guidance on how to create a custom npm package with native module configuration.

I have followed some steps, but I am unsure of how to proceed further and integrate it with my RN app. Additionally, I need help on how to write native iOS/Android code in this package.

Your help would be greatly appreciated.

npx create-react-native-library@latest react-native-dummy

-canOpenURL: failed for URL: "about:srcdoc" - error: "The operation couldn’t be completed. (OSStatus error -10814.)" - ios release build

$
0
0

I have an issue with iframe on production build iOS. Locally works fine but in release build i just get white screen. Foun error message in debugger:

-canOpenURL: failed for URL: "about:srcdoc" - error: "The operation couldn’t be completed. (OSStatus error -10814.)"

Added originWhitelist={['*', "about:srcdoc"]} to WebView.

allowed about scheme in info.plist. Tried adding exception domains. Nothing works.

<key>LSApplicationQueriesSchemes</key><array><string>about</string></array>

Image in SMS using Expo

$
0
0

is it possible to send image in SMS using Expo in react-native.I have the image and I can send text using my application but I would love to send image with the text.Need to work on IOS and AndroidThanks for your help in advance

I tried to use the expo documentation but no results

Issue running "pod install", creating app using expo and need to have in app purchases

$
0
0

when runninng 'npx expo prebuild' i have an issue installing cocoapodsbelow is an error i get running pod install

[!] Unable to find a specification for `RNFBApp` depended upon by `RNFBStorage`You have either: * out-of-date source repos which you can update with `pod repo update` or with `pod install --repo-update`. * mistyped the name or version. * not added the source repo that hosts the Podspec to your Podfile.

Below is a copy of my podfile in the ios directory

require File.join(File.dirname(`node --print "require.resolve('expo/package.json')"`), "scripts/autolinking")require File.join(File.dirname(`node --print "require.resolve('react-native/package.json')"`), "scripts/react_native_pods")require 'json'podfile_properties = JSON.parse(File.read(File.join(__dir__, 'Podfile.properties.json'))) rescue {}ENV['RCT_NEW_ARCH_ENABLED'] = podfile_properties['newArchEnabled'] == 'true' ? '1' : '0'ENV['EX_DEV_CLIENT_NETWORK_INSPECTOR'] = podfile_properties['EX_DEV_CLIENT_NETWORK_INSPECTOR']platform :ios, podfile_properties['ios.deploymentTarget'] || '13.4'install! 'cocoapods',  :deterministic_uuids => falseprepare_react_native_project!# If you are using a `react-native-flipper` your iOS build will fail when `NO_FLIPPER=1` is set.# because `react-native-flipper` depends on (FlipperKit,...), which will be excluded. To fix this,# you can also exclude `react-native-flipper` in `react-native.config.js`## ```js# module.exports = {#   dependencies: {#     ...(process.env.NO_FLIPPER ? { 'react-native-flipper': { platforms: { ios: null } } } : {}),#   }# }# ```flipper_config = FlipperConfiguration.disabledif ENV['NO_FLIPPER'] == '1' then  # Explicitly disabled through environment variables  flipper_config = FlipperConfiguration.disabledelsif podfile_properties.key?('ios.flipper') then  # Configure Flipper in Podfile.properties.json  if podfile_properties['ios.flipper'] == 'true' then    flipper_config = FlipperConfiguration.enabled(["Debug", "Release"])  elsif podfile_properties['ios.flipper'] != 'false' then    flipper_config = FlipperConfiguration.enabled(["Debug", "Release"], { 'Flipper' => podfile_properties['ios.flipper'] })  endenduse_frameworks!target 'Lucky' do  use_expo_modules!  config = use_native_modules!  use_frameworks! :linkage => podfile_properties['ios.useFrameworks'].to_sym if podfile_properties['ios.useFrameworks']  use_frameworks! :linkage => ENV['USE_FRAMEWORKS'].to_sym if ENV['USE_FRAMEWORKS']  use_react_native!(    :path => config[:reactNativePath],    :hermes_enabled => podfile_properties['expo.jsEngine'] == nil || podfile_properties['expo.jsEngine'] == 'hermes',    # An absolute path to your application root.    :app_path => "#{Pod::Config.instance.installation_root}/..",    # Note that if you have use_frameworks! enabled, Flipper will not work if enabled    :flipper_configuration => flipper_config  )  post_install do |installer|    react_native_post_install(      installer,      config[:reactNativePath],      :mac_catalyst_enabled => false    )    # This is necessary for Xcode 14, because it signs resource bundles by default    # when building for devices.    installer.target_installation_results.pod_target_installation_results      .each do |pod_name, target_installation_result|      target_installation_result.resource_bundle_targets.each do |resource_bundle_target|        resource_bundle_target.build_configurations.each do |config|          config.build_settings['CODE_SIGNING_ALLOWED'] = 'NO'        end      end    end  end  post_integrate do |installer|    begin      expo_patch_react_imports!(installer)    rescue => e      Pod::UI.warn e    end  endend

I have had this issue for multiple days and am completely stuck on what to do. I am using an M2 Mac. I have tried to run 'arch -x86_64 pod install' which also does not work.

How to prevent react native modal from moving up when keyboard opens in ios?

$
0
0

I tried to stabilise the modal, but when i touch the screen the modal goes upward and breaking down the style.

<Modal modalVisible={props.visibility} onClose={() => props.onclose()} avoidKeyboard={false}>

<KeyboardAvoidingViewbehavior={Platform.OS === 'ios' ? 'padding' : null`style={{ flex: 1 }}>

<Loading loading={loading} /><Card containerStyle={styles.card}><Text      style={{        color: colors.primaryColor,        fontSize: 18,        ...globalFonts.semiBold,      }}>      {t('ewallet_fund_transfer')}</Text><InputItem      required      title={values[TRANSFER_TO]?.title}      value={values[TRANSFER_TO].value}      errorMessage={values[TRANSFER_TO].error}      onchange={text => {        handleChange(TRANSFER_TO, text);      }}      style={styles.inputItemStyle}      inputContainerStyle={styles.inputContainerStyle}    /><InputItem      currency      keyboardType="decimal-pad"      title={values[AMOUNT].title}      value={values[AMOUNT].value}      errorMessage={values[AMOUNT].error}      onchange={text => {        handleChange(AMOUNT, text);      }}      style={styles.inputItemStyle}      inputContainerStyle={styles.inputContainerStyle}    /><InputItem      currency      editable={false}      disabledStyle={styles.disableStyle}      title={values[AVAILABLE_AMOUNT]?.title}      value={values[AVAILABLE_AMOUNT].value}      errorMessage={values[AVAILABLE_AMOUNT].error}      onchange={text => {        handleChange(AVAILABLE_AMOUNT, text);      }}      style={styles.inputItemStyle}      inputContainerStyle={styles.inputContainerStyle}    /><InputItem      required      secureTextEntry      title={values[TRANS_PASSWORD]?.title}      value={values[TRANS_PASSWORD].value}      errorMessage={values[TRANS_PASSWORD].error}      onchange={text => {        handleChange(TRANS_PASSWORD, text);      }}      style={styles.inputItemStyle}      inputContainerStyle={styles.inputContainerStyle}    /><Button      title={t('submit')}`your text`      buttonStyle={{        backgroundColor: colors.primaryColor,        marginTop: 10,      }}      onPress={() => submitHandler()}    /></Card>
`this is my code and i cant able to understand where i made mistake`

How can I save my credential in expo-secure-sure to reauthenticate later?

$
0
0

I am using expo-apple-authentication with Firebase v9 in Expo Go SDK 50 with React Native. I am able to successfully login with the code below. What I want to do is use expo-secure-store to store whatever information I need from this sign in process to use later (whenever the user opens the app again, that way they don't have to re-login each time). Here is my code:

const signInWithApple = async () => {        try {            const nonce = Math.random().toString(36).substring(2, 10);            Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, nonce)                .then((hashedNonce) =>                    AppleAuthentication.signInAsync({                        requestedScopes: [                            AppleAuthentication.AppleAuthenticationScope.FULL_NAME,                            AppleAuthentication.AppleAuthenticationScope.EMAIL                        ],                        nonce: hashedNonce                    })                )                .then((appleCredential) => {                    const { identityToken } = appleCredential;                    const provider = new OAuthProvider('apple.com');                    const credential = provider.credential({                        idToken: identityToken,                        rawNonce: nonce                    });                    signInWithCredential(auth, credential).then(async (appleCredential) => {                    });                })        } catch (error) {            if (error.code !== 'ERR_CANCELED') Alert.alert('Error', error);        };    };

I have tried storing the identityToken from appleCredential as such: await SecureStore.setItemAsync('userData', JSON.stringify({ 'credential': JSON.stringify({ identityToken }) }));, and then using it like this:

const userData = await SecureStore.getItemAsync('userData');const user = JSON.parse(userData);const { identityToken } = JSON.parse(user.credential);const nonce = Math.random().toString(36).substring(2, 10);const provider = new OAuthProvider('apple.com');const credential = provider.credential({     idToken: identityToken,     rawNonce: nonce});await signInWithCredential(auth, credential);

Although this does not work and returns the error:

FirebaseError: Firebase: Duplicate credential received. Please try again with a new credential. (auth/missing-or-invalid-nonce).

I've also tried storing the nonce from when I sign in, but that returns the same error. I'm pretty stuck. Any help would be greatly appreciated! I'm happy to answer any questions.


Native apps not showing images after upgrade Expo 50 SDK

$
0
0

I have recently upgraded my React Native app from SDK46 to SDK50 and migrated from Webpack to Metro bundler. However, after building the iOS app, I noticed that none of the app's images, both internal and external, are showing up. Strangely, the web version of the app is not experiencing any image-related issues and all the images are showing up as expected.

Expo Build Problem - Unsupported MIME type: image/webp

$
0
0

I'm getting the following errors when building my Expo project for iOS and Android. I'm not using any .webp files anywhere in my project. However, I haven't been able to solve the problem. What do you think could be the issue?

"expo": "^50.0.0","react": "18.2.0","react-native": "0.73.6",

IOS

- Creating native directory (./ios)✔ Created native directory- Updating package.json✔ Updated package.json- Running prebuild✖ Prebuild failedError: [ios.dangerous]: withIosDangerousBaseMod: Unsupported MIME type: image/webpError: [ios.dangerous]: withIosDangerousBaseMod: Unsupported MIME type: image/webp    at Jimp.throwError (/Users/expo/workingdir/build/node_modules/jimp-compact/dist/jimp.js:1:833)    at Jimp.parseBitmap (/Users/expo/workingdir/build/node_modules/jimp-compact/dist/jimp.js:1:125733)    at Jimp.parseBitmap (/Users/expo/workingdir/build/node_modules/jimp-compact/dist/jimp.js:1:8514)    at /Users/expo/workingdir/build/node_modules/jimp-compact/dist/jimp.js:1:7613    at FSReqCallback.readFileAfterClose [as oncomplete] (node:internal/fs/read_file_context:68:3)npx expo prebuild --no-install --platform ios exited with non-zero code: 1

ANDROID

- Creating native directory (./android)✔ Created native directory- Updating package.json✔ Updated package.json- Running prebuild✖ Prebuild failedError: [android.dangerous]: withAndroidDangerousBaseMod: Unsupported MIME type: image/webpError: [android.dangerous]: withAndroidDangerousBaseMod: Unsupported MIME type: image/webp    at Jimp.throwError (/home/expo/workingdir/build/node_modules/jimp-compact/dist/jimp.js:1:833)    at Jimp.parseBitmap (/home/expo/workingdir/build/node_modules/jimp-compact/dist/jimp.js:1:125733)    at Jimp.parseBitmap (/home/expo/workingdir/build/node_modules/jimp-compact/dist/jimp.js:1:8514)    at /home/expo/workingdir/build/node_modules/jimp-compact/dist/jimp.js:1:7613    at FSReqCallback.readFileAfterClose [as oncomplete] (node:internal/fs/read_file_context:68:3)npx expo prebuild --no-install --platform android exited with non-zero code: 1

Google Ad Manager: The ad request was successful, but no ad was returned due to lack of ad inventory OR Request Error: No ad to show

$
0
0

I've integrated the [react-native-ad-manager](https://www.npmjs.com/package/react-native-ad-manager) library into my React Native app to display banner ads at the two places in the app. During testing, both with test ad unit IDs and actual ad unit IDs, the ads displayed correctly. However, after launching the app on the App Store and Play Store, I've encountered an issue where approximately 1 out of 10 times, the ad fails to load, triggering the onAdFailedToLoad function.

The error messages received include:

  • The ad request was successful, but no ad was returned due to lack of ad inventory.
  • Request Error: No ad to show.

with error code: 3

Upon investigation, I've confirmed that there is sufficient inventory available, with thousands of Available Impressions with Likely to deliver status. Despite this, the ads intermittently fail to load.I've tried various troubleshooting steps but haven't been able to resolve the issue. 

Any guidance or workaround would be greatly appreciated.Thank you for your assistance in advance.

Expo crash without any log when submitting images to firebase with Expo Image Picker

$
0
0

I am trying to submit images to firebase Expo crash without any log with Expo Image Picker. But not everytime. Sometimes it works perfect, but sometimes it quits without any error log. I am new and will be happy if anyone helps. I tried several things but result is not change. Here is my code:

import * as ImagePicker from 'expo-image-picker';import { getFirestore, getDocs, collection, addDoc } from "firebase/firestore";import { getDownloadURL, getStorage, ref, uploadBytes } from "firebase/storage"import { app } from '../../firebaseConfig';export default function AddPostScreen() {  const storage = getStorage();  const [images, setImages] = useState([]);  const db = getFirestore(app);  const [uploading, setUploading] = useState(false);  const [selectedImages, setSelectedImages] = useState<string[]>([]);  const [loading, setLoading] = useState(false);const pickImages = async () => {    let result = await ImagePicker.launchImageLibraryAsync({      mediaTypes: ImagePicker.MediaTypeOptions.Images,      allowsMultipleSelection: true,      allowsEditing: false,      quality: 0,      base64: true,    });    if (!result.canceled) {      const uris = result?.assets.map((image) => image.uri) ?? [];      setSelectedImages(uris);    }  };const onSubmitMethod = async (values: any) => {    setLoading(true);    values.image = selectedImages;    values.postId = Date.now().toString();    const imagePromises = selectedImages.map(async (uri, index) => {      const response = await fetch(uri);      const blob = await response.blob();      const imageName = `userPost/${Date.now()}_${index}`; // Unique image name      const storageRef = ref(storage, imageName);      setUploading(true); // Start uploading      await uploadBytes(storageRef, blob);      setUploading(false); // Finish uploading      const downloadURL = await getDownloadURL(storageRef);      return downloadURL;    });    const imageUrls = await Promise.all(imagePromises);    values.images = imageUrls;    values.userName = user.fullName;    values.userEmail = user.primaryEmailAddress.emailAddress;    values.userImage = user.imageUrl;    console.log('Images uploaded:', imageUrls);    // Add the document with the image URLs to the collection    const docRef = await addDoc(collection(db, 'UserPost'), values);    if (docRef.id) {      setLoading(false);      Alert.alert('Təbriklər!', 'Elan uğurla əlavə edildi!')      // Clear the selected images after upload      setSelectedImages([]);    }  };return (

Error Domain=NSOSStatusErrorDomain Code=-50 when setCategory RTCAudioSession to AVAudioSessionCategoryPlayback

$
0
0

I'm writing a react native code to watch livestream by using WebRTC plugin. The default audio session category is AVAudioSessionCategoryPlayAndRecord, that make some problems: poor sound quality than media speaker, inability to set volume to 0, and moreover, it requires microphone access.

When I try to setCategory of RTCAudioSession to AVAudioSessionCategoryPlayback. I encountered this error: Error Domain=NSOSStatusErrorDomain Code=-50 "(null)"

This is my native code, I call it in didFinishLaunchingWithOptions of AppDelegate.m

  @try {    NSError *error = nil;    RTCAudioSession* session = [RTCAudioSession sharedInstance];    RTCAudioSessionConfiguration* config = [RTCAudioSessionConfiguration webRTCConfiguration];    [session lockForConfiguration];    config.category = AVAudioSessionCategoryPlayback;    config.categoryOptions = AVAudioSessionCategoryOptionDefaultToSpeaker;    [session setCategory:config.category withOptions:config.categoryOptions error:&error];    if (error) {        NSLog(@"LMT Error setCategory: %@", error);    } else {        NSLog(@"LMT Audio session setCategory successfully.");    }    [session setMode:config.mode error:&error];    if (error) {        NSLog(@"LMT Error setMode: %@", error);    } else {        NSLog(@"LMT Audio session setMode successfully.");    }    [session unlockForConfiguration];  } @catch (NSException *exception) {    NSLog(@"LMT Error: %@", exception);  }}

The error:

Error Domain=NSOSStatusErrorDomain Code=-50 "(null)"

I want to change it to AVAudioSessionCategoryPlayback for play stream with media speaker

Platform Information

  • React Native Version: 0.71.30.63.4
  • WebRTC Module Version: 111.0.6
  • Platform OS + Version: IOS

iOS background notification handler issue using @react-native-firebase/messaging

$
0
0

I am facing the issue when the app is in background or closed state. The notifications are shown in the notification center in all cases but the messaging().setBackgroundMessageHandler doesn't get called every time but only some times while checked rigorously on the app. Followed the official documentation for cloud messaging, upgraded to version 10.2.0 for @react-native-firebase/messaging and @react-native-firebase/app. All the states callbacks are working fine in Android and obtained perfectly every time, the issues exist only for iOS and not sure what is causing all this mess.

Adding here code for ref that I am using.In the entry file i.e. index.js

messaging().setBackgroundMessageHandler(async (remoteMessage) => {  console.log("Message handled in the background! 1", remoteMessage);});function HeadlessCheck({ isHeadless }) {  if (isHeadless) {    // App has been launched in the background by iOS, ignore    return null;  }  return <App />;}AppRegistry.registerComponent(appName, () => HeadlessCheck);

In App.js:

const App = () => {  var notif = new NotifService();  useEffect(() => {    requestUserPermission()    checkPermission()    console.log("checkPermission")    const unsubscribe = messaging().onMessage(async remoteMessage => {      console.log("A new FCM message arrived!: foreground: ", remoteMessage)      console.log("A new FCM message arrived!: foreground: ", remoteMessage.messageId)      // Alert.alert('A new FCM message arrived!: foreground: ', JSON.stringify(remoteMessage));      notif.localNotif();    });    return unsubscribe;  }, []);  useEffect(() => {    messaging().onNotificationOpenedApp(remoteMessage => {      console.log('Notification caused app to open from background state:',        remoteMessage.notification,      );      Alert.alert('Message handled in the background state!', JSON.stringify(remoteMessage));      // navigation.navigate(remoteMessage.data.type);    });    // Check whether an initial notification is available    messaging()      .getInitialNotification()      .then(remoteMessage => {        if (remoteMessage) {          console.log('Notification caused app to open from quit state:',            remoteMessage.notification,          );          Alert.alert('Message handled in the quit state!', JSON.stringify(remoteMessage));          // setInitialRoute(remoteMessage.data.type); // e.g. "Settings"        }        // setLoading(false);      });  }, []);  async function requestUserPermission() {    const authStatus = await messaging().requestPermission();    const enabled =      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||      authStatus === messaging.AuthorizationStatus.PROVISIONAL;    if (enabled) {      console.log('Authorization status:', authStatus);    }  }    // 1    async function checkPermission() {      const enabled = await messaging().hasPermission();      console.log("checkPermission: enabled: ", enabled)      if (enabled) {        getToken();      } else {        requestPermission();      }    }    // 3    async function getToken() {      let fcmToken = await AsyncStorage.getItem('fcmToken');      console.log('fcmToken @@1:', fcmToken);      if (!fcmToken) {        fcmToken = await messaging().getToken();        console.log('fcmToken @@2:', fcmToken);        if (fcmToken) {          // user has a device token          await AsyncStorage.setItem('fcmToken', fcmToken);        }      }    }    // 2    async function requestPermission() {      console.log("requestPermission:")      try {        await messaging().requestPermission();        // User has authorised        getToken();      } catch (error) {        // User has rejected permissions        console.log('permission rejected');      }    }}

Payload that I tested using firebase rest API:

{ "to": "TOKEN_HERE", "data": { "notification": { "title": "ABC1", "body": "xyz1" }, "Name": "121" }, "notification": { "title": "ABC1", "body": "xyz1" }, "priority": "high", "content_available": true }

Please add here if anybody faced same issue and resolved that. Stuck for days with this now! Thanks.

React native IOS build cant find libraries in Derived Data directory

$
0
0

I am coming back to a React Native project which used to build and now is not.

I have tried the following;

  1. Updateing react/react native
  2. Removing and re-installing node modules
  3. Remove and reinstalling cocapods
  4. Updating cocapods
  5. Cleaing the build directory
  6. Removing and resetting the library search paths in xcode
  7. Updating the IOS build target in both xcode and the Podfile

The probelm I am having is when I build the project I see that it cannot find the DoubleConversion library.

After some investigation it turns out this is just the first library it cannot find so errors on this one. During a pod install I can see it installing the DoubleConversion library.

This is the output I get from running the IOS build command. Note the build output is the same building from the terminal or via xcode.

yarn iosyarn run v1.22.19$ react-native run-ios --simulator='iPhone 15 Pro'info A dev server is already running for this project on port 8081.info Found Xcode workspace "myperks.xcworkspace"info Launching iPhone 15 Pro (iOS 17.0)info Building (using "xcodebuild -workspace myperks.xcworkspace -configuration Debug -scheme myperks -destination id=D95E730E-FB5A-4D9A-8404-0189D398D230")Ignoring digest-crc-0.6.4 because its extensions are not built. Try: gem pristine digest-crc --version 0.6.4Ignoring unf_ext-0.0.8.2 because its extensions are not built. Try: gem pristine unf_ext --version 0.0.8.2▸ Running script '[CP] Check Pods Manifest.lock'▸ Running script 'Start Packager'▸ Processing Info.plist▸ Linking myperks⚠️  ld: ignoring duplicate libraries: '-lc++'⚠️  ld: search path '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator17.4.sdk/usr/lib/swift/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator17.4.sdk/usr/lib/swift' not found⚠️  ld: search path '/Users/chris/Library/Developer/Xcode/DerivedData/myperks-gdtrvukhkrhlaydznulsqeffucrm/Build/Products/Debug-iphonesimulator/DoubleConversion' not found⚠️  ld: search path '/Users/chris/Library/Developer/Xcode/DerivedData/myperks-gdtrvukhkrhlaydznulsqeffucrm/Build/Products/Debug-iphonesimulator/RCT-Folly' not found

There are more libs it fails to find but it cut it off there for the example.

What I noticed is the directory that the build in looking in for libs doesnt actually exist.

/Users/chris/Library/Developer/Xcode/DerivedData/myperks-gdtrvukhkrhlaydznulsqeffucrm/Build/Products/Debug-iphonesimulator

The above exists, however inside this is another dir named after the app e.g. myperks.app, this has a few buits and a Frameworks dir but does not have RCT-Folly for example.


how to create a custom selector function in React Native that appends selected text to the clipboard

$
0
0

I need to append my email address after the copied content.eg: Suppose i selected "Hello world" from Text component, so i want that the clipboard should have "Hello world Contact me: abc@gmail.com".

<Text  key={Math.random()}  selectable={true}  selectionColor="orange"  style={[  styles.lyricsText,     {       fontSize: fontSizeCount,       alignSelf: 'flex-end'     },   ]}>    Hello world, I am using react native, and exploring features in react native clipboard.  </Text>

I have used the react-native-clipboard/clipboard and tried on add lister, but that won't work since it will fall in infinite loop to add the text.

The code i used for setting that additional text to clipboard is like

 const [clipBoardString, setClipBoardString] = useState('');    const clipBoardStringRef = useRef('');    const setIosClipBoard = useCallback(async (initialString) => {        clipBoardStringRef.current = initialString.join('');        clipBoardStringRef.current += ' Read more at shaivam.org';        Clipboard.setStrings(clipBoardStringRef.current);    });    const setAndroidClipBoard = useCallback(async (initialString) => {        clipBoardStringRef.current = initialString;        clipBoardStringRef.current += ' Read more at shaivam.org';        Clipboard.setString(clipBoardStringRef.current);    }, []);    const fetchClipBoardString = useCallback(async () => {        return Platform.select({            ios: Clipboard.getStrings(),            android: Clipboard.getString(),        });    }, []);    useEffect(() => {        Clipboard.addListener(() => {            fetchClipBoardString().then((string) => {                setClipBoardString((prev) => string);            });        });        return () => Clipboard.removeAllListeners();    }, []);    useEffect(() => {        if (clipBoardString) {            Platform.select({                ios: setIosClipBoard(clipBoardString),                android: setAndroidClipBoard(clipBoardString),            });        }    }, [clipBoardString]);

So,is there any approach or callback that i am missing to add in text through which i can achieve this.

How to redirect a user to AppStore with query params you want to access after installing the app?

$
0
0

So essentially, what I want to achieve is to route the user to AppStore/PlayStore via the itunes/playstore links with some information appended to the url and then gain access to the query params in that url after the user has installed the app.

Example: http://itunes.apple.com/us/app/${appName}/${appID}?userID=${userID}&amount=${amount}

And still have access to userID and amount when the app is launched.

Only last notification appears on iOS after switching to online

$
0
0

regards documentation of Firebase I have (I suppose) collapsible message.I had a similar problem with Android, but after removing the whole notification object from the payload it started working.But on iOS sending notification with (only) data as payload nothing helped - only last notification appears after switching network from offline to online.

Honestly, I tried many different ways (with or without apns header, without apns etc.) and I see a dead end. Help!

For now, my payload looks:

message: {  token: 'some token',  data: {    title: 'some title',    body: 'some body',    content_available: 'true',    priority: 'high'  }}

I'm using:

System:    OS: macOS 12.7.4    CPU: (8) x64 Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz    Memory: 3.49 GB / 16.00 GB    Shell: 5.8.1 - /bin/zsh  Binaries:    Node: 16.17.1 - ~/.nvm/versions/node/v16.17.1/bin/node    Yarn: 1.22.19 - ~/.nvm/versions/node/v16.17.1/bin/yarn    npm: 9.8.1 - ~/.nvm/versions/node/v16.17.1/bin/npm    Watchman: 2024.01.22.00 - /usr/local/bin/watchman  Managers:    CocoaPods: 1.15.2 - /Users/darek/.rvm/gems/ruby-2.6.5/bin/pod  SDKs:    iOS SDK:      Platforms: DriverKit 22.2, iOS 16.2, macOS 13.1, tvOS 16.1, watchOS 9.1    Android SDK: Not Found  IDEs:    Android Studio: 2022.3 AI-223.8836.35.2231.10671973    Xcode: 14.2/14C18 - /usr/bin/xcodebuild  Languages:    Java: 11.0.21 - /usr/local/opt/openjdk@11/bin/javac  npmPackages:    @react-native-community/cli: Not Found    react: 18.2.0 => 18.2.0    react-native: 0.71.17 => 0.71.17    react-native-macos: Not Found
"@notifee/react-native": "7.8.0",and"@react-native-firebase/analytics": "19.2.2","@react-native-firebase/app": "19.2.2","@react-native-firebase/messaging": "19.2.2",(also tried 18.8.0, 18.9.0)

Getting an App Store ID without publishing an iOS app

$
0
0

I'm currently developing a React Native app, which will be published on the iOS App Store eventually.

I'm currently attempting to build deep links within the app, but I require an App Store ID before I can do this.

Having searched on Google - there's no current answers to this query, but it feels quite important, and I can't find any documentation on it.

Does anyone know if it's possible to get an App Store ID without publishing the app?

Opposite sides on the different platforms

$
0
0

In my React Native app, I have the following style for my container:

const styles = StyleSheet.create({  container: {    position: "absolute",    top: 25,    right: 30,  },});

On Android, the container is on the top Left side, but on iPhone, it is on the top right side.

Why it happens?How do I set the same side for both?

Viewing all 17237 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>