import { ConfigPlugin, withAppDelegate, withInfoPlist, withDangerousMod, withXcodeProject, withEntitlementsPlist } from '@expo/config-plugins' import { SmartechPushProps } from './smartechPushProps' import { promises as fsPromises } from 'fs'; import path from 'path'; import fs from 'fs'; import { Helper } from './helper' import { appDelegateHeader, DEFAULT_BUNDLE_SHORT_VERSION, DEFAULT_BUNDLE_VERSION, importSmartPush, interfaceDelegate, IPHONEOS_DEPLOYMENT_TARGET, NCE, NCE_EXT_FILES, NCE_PODFILE_REGEX, NCE_SOURCE_FILE, NCE_TARGET_NAME, NSE, NSE_EXT_FILES, NSE_PODFILE_REGEX, NSE_SOURCE_FILE, NSE_TARGET_NAME, TARGETED_DEVICE_FAMILY, swiftImports, swiftBridgingHeaderImports, SWIFT_NSE, SWIFT_NCE } from './iosConstants'; import { FileManager } from './fileManager'; import { NSEUpdaterManager, NCEExtensionManager } from './extensionManager'; import getEasManagedCredentialsConfigExtra from './getManagedEas'; import { ExpoConfig } from '@expo/config-types'; // Swift helper functions import { swiftPushDelegateSnippet, swiftRegisterForNotificationSnippet, swiftFailToRegisterForNotificationSnippet, swiftUserNotificationDelegateSnippet } from './iosConstants'; const updateSwiftBridgingHeader = async (platformProjectRoot: string, projectName: string): Promise => { const bridgingHeaderPath = path.join(platformProjectRoot, projectName, `${projectName}-Bridging-Header.h`); try { let bridgingHeaderContents = ''; try { bridgingHeaderContents = await fsPromises.readFile(bridgingHeaderPath, 'utf-8'); } catch (error) { // File doesn't exist, create it with default content bridgingHeaderContents = '//\n// Use this file to import your target\'s public headers that you would like to expose to Swift.\n//\n\n'; } const lines = bridgingHeaderContents.split('\n'); let modified = false; // Add each import if not already present for (const importLine of swiftBridgingHeaderImports) { if (!lines.some(line => line.trim() === importLine)) { lines.push(importLine); modified = true; console.log(`${importLine} added to bridging header`); } } if (modified) { await fsPromises.writeFile(bridgingHeaderPath, lines.join('\n'), 'utf-8'); console.log(`Updated bridging header at ${bridgingHeaderPath}`); } } catch (error) { console.error(`Error updating bridging header: ${error}`); } }; const addSwiftPushDelegateCode = (contents: string, props: SmartechPushProps): string => { const lines = contents.split("\n"); // Find didFinishLaunchingWithOptions method by looking for the specific method name let didLaunchIndex = -1; for (let i = 0; i < lines.length; i++) { const line = lines[i]; if (/(?:public\s+)?(?:override\s+)?func\s+application\s*\(/.test(line)) { // Check the next 5 lines for didFinishLaunchingWithOptions for (let j = i; j < Math.min(i + 5, lines.length); j++) { if (lines[j].includes('didFinishLaunchingWithOptions')) { didLaunchIndex = i; break; } } if (didLaunchIndex !== -1) break; } } if (didLaunchIndex === -1) { console.log('Could not find didFinishLaunchingWithOptions method in Swift AppDelegate'); return contents; } // Find the opening brace of the method let methodStartIndex = didLaunchIndex; for (let i = didLaunchIndex; i < lines.length; i++) { if (lines[i].includes('{')) { methodStartIndex = i; break; } } // Get the snippet based on autoAskNotificationPermission config const snippet = swiftPushDelegateSnippet(props.autoAskNotificationPermission); // Add the push delegate snippets after the method opening brace const resultLines = [ ...lines.slice(0, methodStartIndex + 1), ...snippet, ...lines.slice(methodStartIndex + 1), ]; console.log('Swift push delegate initialization code added to didFinishLaunchingWithOptions'); return resultLines.join("\n"); }; const addSwiftDelegateConformance = (contents: string): string => { const lines = contents.split("\n"); // Find the AppDelegate class declaration line let classDeclarationIndex = -1; for (let i = 0; i < lines.length; i++) { const line = lines[i].trim(); if (line.includes('class') && line.includes('AppDelegate') && line.includes(':')) { classDeclarationIndex = i; break; } } if (classDeclarationIndex === -1) { console.log('Could not find AppDelegate class declaration in Swift file'); return contents; } // Check and add delegates to the class declaration let classLine = lines[classDeclarationIndex]; let modified = false; if (!classLine.includes('UNUserNotificationCenterDelegate')) { // Add UNUserNotificationCenterDelegate to the class declaration classLine = classLine.replace('{', ', UNUserNotificationCenterDelegate {'); console.log('Added UNUserNotificationCenterDelegate conformance to Swift AppDelegate'); modified = true; } if (!classLine.includes('SmartechDelegate')) { // Add SmartechDelegate to the class declaration classLine = classLine.replace('{', ', SmartechDelegate {'); console.log('Added SmartechDelegate conformance to Swift AppDelegate'); modified = true; } if (modified) { lines[classDeclarationIndex] = classLine; } return lines.join("\n"); }; const addSwiftPushMethods = (contents: string): string => { const lines = contents.split("\n"); // Find the end of the main AppDelegate class let classEndIndex = -1; let insideAppDelegate = false; let braceCount = 0; for (let i = 0; i < lines.length; i++) { const line = lines[i].trim(); // Look for the AppDelegate class declaration if (line.includes('class') && line.includes('AppDelegate') && line.includes(':')) { insideAppDelegate = true; braceCount = 0; } if (insideAppDelegate) { // Count braces to find the end of the AppDelegate class const openBraces = (line.match(/\{/g) || []).length; const closeBraces = (line.match(/\}/g) || []).length; braceCount += openBraces - closeBraces; // When we reach the closing brace of AppDelegate class if (braceCount === 0 && line.includes('}') && openBraces === 0) { classEndIndex = i; break; } } } if (classEndIndex === -1) { console.log('Could not find AppDelegate class end in Swift file'); return contents; } // Prepare methods to add const methodsToAdd = [ swiftRegisterForNotificationSnippet.registerNotificationFunction, '', swiftFailToRegisterForNotificationSnippet.failToRegisterFunction, swiftUserNotificationDelegateSnippet ]; const resultLines = [ ...lines.slice(0, classEndIndex), ...methodsToAdd, ...lines.slice(classEndIndex), ]; console.log('Swift push notification methods added to AppDelegate class'); return resultLines.join("\n"); }; const withPushiOS: ConfigPlugin = (config, props) => { config = handleNotificationServiceExtension(config, props); config = handleNotificationContentExtension(config, props); config = modifyPodfileForNCE(config); config = modifyPodfileForNSE(config); config = setUpNSETargetInXcode(config, props); config = setUpNCETargetInXcode(config, props); config = modifyAppDelegateHeader(config, props); config = modifyAppDelegateImplementation(config, props); config = withRemoteNotificationsPermissions(config, props); config = withAppEnvironment(config, props); config = withEasManagedCredentials(config, props); return config; } const withEasManagedCredentials: ConfigPlugin = (config) => { config.extra = getEasManagedCredentialsConfigExtra(config as ExpoConfig); return config; } const withAppEnvironment: ConfigPlugin = ( config, props ) => { return withEntitlementsPlist(config, (newConfig) => { newConfig.modResults["aps-environment"] = props.ios.mode.toString(); return newConfig; }); }; const modifyAppDelegateHeader: ConfigPlugin = (config, props) => { return withDangerousMod(config, [ 'ios', async (config) => { const { platformProjectRoot, projectName } = config.modRequest; if (platformProjectRoot && projectName) { const isSwift = await Helper.Ios.isSwiftProject(platformProjectRoot, projectName); if (isSwift) { // Handle Swift AppDelegate const appDelegateSwiftPath = path.join(platformProjectRoot, projectName, 'AppDelegate.swift'); const appDelegateSwiftContents = await fsPromises.readFile(appDelegateSwiftPath, 'utf-8'); // Update bridging header for Swift projects to expose React Native module headers // await updateSwiftBridgingHeader(platformProjectRoot, projectName); // Add SmartPush and UserNotifications imports if not already present const lines = appDelegateSwiftContents.split('\n'); let modified = false; // Check for SmartPush import if (!lines.some(line => line.trim() === swiftImports.smartPushImport)) { // Find the right place to insert import (after other imports) let insertIndex = 0; for (let i = 0; i < lines.length; i++) { if (lines[i].startsWith('import ')) { insertIndex = i + 1; } else if (lines[i].trim() === '' && insertIndex > 0) { break; } } lines.splice(insertIndex, 0, swiftImports.smartPushImport); modified = true; console.log(`${swiftImports.smartPushImport} added to AppDelegate.swift`); } // Check for UserNotifications import if (!lines.some(line => line.trim() === swiftImports.userNotificationsImport)) { // Find the right place to insert import (after other imports) let insertIndex = 0; for (let i = 0; i < lines.length; i++) { if (lines[i].startsWith('import ')) { insertIndex = i + 1; } else if (lines[i].trim() === '' && insertIndex > 0) { break; } } lines.splice(insertIndex, 0, swiftImports.userNotificationsImport); modified = true; console.log(`${swiftImports.userNotificationsImport} added to AppDelegate.swift`); } if (modified) { const modifiedContents = lines.join('\n'); await fsPromises.writeFile(appDelegateSwiftPath, modifiedContents, 'utf-8'); } } else { // Handle Objective-C AppDelegate (original logic) const appDelegateHeaderPath = path.join( platformProjectRoot, projectName, appDelegateHeader ); const appDelegateHeaderContents = await fsPromises.readFile( appDelegateHeaderPath, "utf-8" ); // Check if import is already present then dont add it again if (!appDelegateHeaderContents.includes(importSmartPush)) { const modifiedAppDelegateHeaderContents = Helper.Ios.addSmartPushToAppDelegate( appDelegateHeaderContents, importSmartPush, interfaceDelegate ); await FileManager.writeFile(appDelegateHeaderPath, modifiedAppDelegateHeaderContents); } else { console.log(`${importSmartPush} is already added.`) } } } return config; } ]); } const modifyAppDelegateImplementation: ConfigPlugin = (config, props) => { return withDangerousMod(config, [ 'ios', async (config) => { const { platformProjectRoot, projectName } = config.modRequest; if (platformProjectRoot && projectName) { const isSwift = await Helper.Ios.isSwiftProject(platformProjectRoot, projectName); if (isSwift) { // Handle Swift AppDelegate const appDelegateSwiftPath = path.join(platformProjectRoot, projectName, 'AppDelegate.swift'); let contents = await fsPromises.readFile(appDelegateSwiftPath, 'utf-8'); // Add delegate conformance to class declaration contents = addSwiftDelegateConformance(contents); // Add push delegate initialization code to didFinishLaunchingWithOptions contents = addSwiftPushDelegateCode(contents, props); // Add push notification methods to the AppDelegate class contents = addSwiftPushMethods(contents); await fsPromises.writeFile(appDelegateSwiftPath, contents, 'utf-8'); console.log('Swift AppDelegate push implementation updated successfully'); } else { // Handle Objective-C AppDelegate (original logic using withAppDelegate internally) const appDelegatePath = await Helper.Ios.getObjCAppDelegatePath(platformProjectRoot, projectName); let contents = await fsPromises.readFile(appDelegatePath, 'utf-8'); // Import statements const importContents = Helper.modifyImportContents(contents.split("\n")); const didFinishLaunchContents = Helper.modifyDidFinishLaunchContents(importContents, props); //RegisterForRemoteNotificationsContents modifications const registerRemoteNotificationContents = Helper.modifyRegisterForRemoteNotificationsContents(didFinishLaunchContents); //FailToRegisterForRemoteNotificationsContents modifications const failToRegisterForRemoteNotificationsContents = Helper.modifyFailToRegisterForRemoteNotificationsContents( registerRemoteNotificationContents ); //smartechDelegate modifications const smartechDelegateContents = Helper.addUserNotifictionCenterDelegate( failToRegisterForRemoteNotificationsContents ); await fsPromises.writeFile(appDelegatePath, smartechDelegateContents, 'utf-8'); console.log('Objective-C AppDelegate push implementation updated successfully'); } } return config; } ]); } const withRemoteNotificationsPermissions: ConfigPlugin = ( config ) => { const BACKGROUND_MODE_KEYS = ["remote-notification"]; return withInfoPlist(config, (newConfig) => { if (!Array.isArray(newConfig.modResults.UIBackgroundModes)) { newConfig.modResults.UIBackgroundModes = []; } for (const key of BACKGROUND_MODE_KEYS) { if (!newConfig.modResults.UIBackgroundModes.includes(key)) { newConfig.modResults.UIBackgroundModes.push(key); } } return newConfig; }); }; const handleNotificationServiceExtension: ConfigPlugin = (config, props) => { return withDangerousMod(config, [ "ios", async (config) => { const iosPath = path.join(config.modRequest.projectRoot, 'ios'); const projectName = config.name || 'YourProject'; // Detect if project is Swift or Objective-C const isSwift = await Helper.Ios.isSwiftProject(iosPath, projectName); // Use appropriate constants based on project type const nseConfig = isSwift ? SWIFT_NSE : NSE; const assetPath = isSwift ? 'Swift' : 'ObjC'; const sourceDir = path.resolve( __dirname, '..', 'assets', assetPath, nseConfig.folderName ); fs.mkdirSync(`${iosPath}/${nseConfig.targetName}`, { recursive: true }); for (const extFile of nseConfig.extFiles) { const targetFile = `${iosPath}/${nseConfig.targetName}/${extFile}`; await FileManager.copyFile(`${sourceDir}/${extFile}`, targetFile); } // Copy NSE source file either from configuration-provided location, falling back to the default one. const sourcePath = `${sourceDir}/${nseConfig.sourceFileName}`; const targetFile = `${iosPath}/${nseConfig.targetName}/${nseConfig.sourceFileName}`; if (fs.existsSync(sourcePath) && !fs.existsSync(targetFile)) { await FileManager.copyFile(sourcePath, targetFile); } const nseGroupName = props.ios.groupIdentifier; /* MODIFY COPIED EXTENSION FILES */ const nseUpdater = new NSEUpdaterManager(iosPath); await nseUpdater.updateNSEEntitlements( `group.${props.ios.groupIdentifier}` ); await nseUpdater.updateNSEBundleVersion( config.ios?.buildNumber ?? DEFAULT_BUNDLE_VERSION, `group.${nseGroupName}` ); await nseUpdater.updateNSEBundleShortVersion( config?.version ?? DEFAULT_BUNDLE_SHORT_VERSION ); return config; }, ]); } const handleNotificationContentExtension: ConfigPlugin = (config, props) => { return withDangerousMod(config, [ 'ios', async (config) => { const iosPath = path.join(config.modRequest.projectRoot, 'ios'); const projectName = config.name || 'YourProject'; // Detect if project is Swift or Objective-C const isSwift = await Helper.Ios.isSwiftProject(iosPath, projectName); // Use appropriate constants based on project type const nceConfig = isSwift ? SWIFT_NCE : NCE; const assetPath = isSwift ? 'Swift' : 'ObjC'; const sourceDir = path.resolve( __dirname, '..', 'assets', assetPath, nceConfig.folderName ); // Use fs to create directories synchronously fs.mkdirSync(`${iosPath}/${nceConfig.targetName}`, { recursive: true }); // Implement copyFolderSync to copy all files from sourceDir to destinationDir FileManager.copyFolderAsync(sourceDir, `${iosPath}/${nceConfig.targetName}`); // Copy NCE source file either from configuration-provided location, falling back to the default one. const sourcePath = `${sourceDir}/${nceConfig.sourceFileName}`; const targetFile = `${iosPath}/${nceConfig.targetName}/${nceConfig.sourceFileName}`; if (fs.existsSync(sourcePath) && !fs.existsSync(targetFile)) { await FileManager.copyFile(sourcePath, targetFile); } const nceGroupName = props.ios.groupIdentifier; /* MODIFY COPIED EXTENSION FILES */ const nceUpdater = new NCEExtensionManager(iosPath); await nceUpdater.updateNCEEntitlements( `group.${props.ios.groupIdentifier}` ); await nceUpdater.updateNCEBundleVersion( config.ios?.buildNumber ?? DEFAULT_BUNDLE_VERSION, `group.${nceGroupName}` ); await nceUpdater.updateNCEBundleShortVersion( config?.version ?? DEFAULT_BUNDLE_SHORT_VERSION ); // Setup custom notification icon if provided await nceUpdater.setupCustomNotificationIcon(props, config.modRequest.projectRoot); return config; }, ]); } const setUpNCETargetInXcode: ConfigPlugin = (config, props) => { return withXcodeProject(config, async (newConfig) => { const xcodeProject = newConfig.modResults; const iosPath = path.join(newConfig.modRequest.projectRoot, 'ios'); const projectName = newConfig.name || 'YourProject'; // Detect if project is Swift or Objective-C const isSwift = await Helper.Ios.isSwiftProject(iosPath, projectName); // Use appropriate constants based on project type const nceConfig = isSwift ? SWIFT_NCE : NCE; if (!!xcodeProject.pbxTargetByName(nceConfig.targetName)) { // Target already exists, skipping... return newConfig; } if (!xcodeProject.pbxGroupByName(nceConfig.targetName)) { //TODO: // Create new PBXGroup for the extension // og // const extGroup = xcodeProject.addPbxGroup( // [...nceConfig.extFiles, nceConfig.sourceFileName, "Base.lproj/MainInterface.storyboard"], // nceConfig.targetName, // nceConfig.targetName // ); const extGroup = xcodeProject.addPbxGroup( [...nceConfig.extFiles, nceConfig.sourceFileName, "Base.lproj/MainInterface.storyboard", "Media.xcassets"], nceConfig.targetName, nceConfig.targetName ); // // Add the new PBXGroup to the top-level group const groups = xcodeProject.hash.project.objects["PBXGroup"]; Object.keys(groups).forEach((key) => { if (typeof groups[key] === 'object' && groups[key].name === undefined && groups[key].path === undefined) { xcodeProject.addToPbxGroup(extGroup.uuid, key); } }); // WORK AROUND for codeProject.addTarget BUG const projObjects = xcodeProject.hash.project.objects; projObjects["PBXTargetDependency"] = projObjects["PBXTargetDependency"] || {}; projObjects["PBXContainerItemProxy"] = projObjects["PBXContainerItemProxy"] || {}; // Add the NCE target const nceTarget = xcodeProject.addTarget( nceConfig.targetName, "app_extension", nceConfig.targetName, `${config.ios?.bundleIdentifier}.${nceConfig.targetName}` ); // Add build phases to the new target xcodeProject.addBuildPhase( [nceConfig.sourceFileName], "PBXSourcesBuildPhase", "Sources", nceTarget.uuid ); // Add storyboard for NCE (both Swift and ObjC use same path) xcodeProject.addBuildPhase( ["Base.lproj/MainInterface.storyboard", "Media.xcassets"], "PBXResourcesBuildPhase", "Resources", nceTarget.uuid ); // xcodeProject.addBuildPhase( // [], // "PBXResourcesBuildPhase", // "Resources", // nceTarget.uuid // ); xcodeProject.addBuildPhase( ["UserNotifications.framework", "UserNotificationsUI.framework"], "PBXFrameworksBuildPhase", "Frameworks", nceTarget.uuid ); // Edit the Deployment info of the new Target const configurations = xcodeProject.pbxXCBuildConfigurationSection(); for (const key in configurations) { if (typeof configurations[key].buildSettings !== "undefined" && configurations[key].buildSettings.PRODUCT_NAME === `"${nceConfig.targetName}"`) { const buildSettingsObj = configurations[key].buildSettings; buildSettingsObj.DEVELOPMENT_TEAM = props.ios.devTeam; buildSettingsObj.IPHONEOS_DEPLOYMENT_TARGET = props.ios.iPhoneDeploymentTarget ?? IPHONEOS_DEPLOYMENT_TARGET; buildSettingsObj.TARGETED_DEVICE_FAMILY = TARGETED_DEVICE_FAMILY; buildSettingsObj.CODE_SIGN_ENTITLEMENTS = `${nceConfig.targetName}/${nceConfig.targetName}.entitlements`; buildSettingsObj.CODE_SIGN_STYLE = "Automatic"; // Add Swift version for Swift projects if (isSwift) { buildSettingsObj.SWIFT_VERSION = props.ios.swiftVersion ?? "5.0"; } } } // Add development teams to both your target and the original project xcodeProject.addTargetAttribute( "DevelopmentTeam", props.ios.devTeam, nceTarget ); xcodeProject.addTargetAttribute("DevelopmentTeam", props.ios.devTeam); } return newConfig; }); }; const setUpNSETargetInXcode: ConfigPlugin = (config, props) => { return withXcodeProject(config, async (newConfig) => { const xcodeProject = newConfig.modResults; const iosPath = path.join(newConfig.modRequest.projectRoot, 'ios'); const projectName = newConfig.name || 'YourProject'; // Detect if project is Swift or Objective-C const isSwift = await Helper.Ios.isSwiftProject(iosPath, projectName); // Use appropriate constants based on project type const nseConfig = isSwift ? SWIFT_NSE : NSE; if (xcodeProject.pbxTargetByName(nseConfig.targetName)) { // Target already exists, skipping... return newConfig; } if (!xcodeProject.pbxGroupByName(nseConfig.targetName)) { // Create new PBXGroup for the extension const extGroup = xcodeProject.addPbxGroup( [...nseConfig.extFiles, nseConfig.sourceFileName], nseConfig.targetName, nseConfig.targetName ); // Add the new PBXGroup to the top level group const groups = xcodeProject.hash.project.objects["PBXGroup"]; Object.keys(groups).forEach((key) => { if (typeof groups[key] === 'object' && groups[key].name === undefined && groups[key].path === undefined) { xcodeProject.addToPbxGroup(extGroup.uuid, key); } }); // WORK AROUND for codeProject.addTarget BUG const projObjects = xcodeProject.hash.project.objects; projObjects["PBXTargetDependency"] = projObjects["PBXTargetDependency"] || {}; projObjects["PBXContainerItemProxy"] = projObjects["PBXContainerItemProxy"] || {}; // Add the NSE target const nseTarget = xcodeProject.addTarget( nseConfig.targetName, "app_extension", nseConfig.targetName, `${config.ios?.bundleIdentifier}.${nseConfig.targetName}` ); // Add build phases to the new target xcodeProject.addBuildPhase( [nseConfig.sourceFileName], "PBXSourcesBuildPhase", "Sources", nseTarget.uuid ); xcodeProject.addBuildPhase( [], "PBXResourcesBuildPhase", "Resources", nseTarget.uuid ); xcodeProject.addBuildPhase( [], "PBXFrameworksBuildPhase", "Frameworks", nseTarget.uuid ); // Edit the Deployment info of the new Target const configurations = xcodeProject.pbxXCBuildConfigurationSection(); for (const key in configurations) { if (typeof configurations[key].buildSettings !== "undefined" && configurations[key].buildSettings.PRODUCT_NAME === `"${nseConfig.targetName}"`) { const buildSettingsObj = configurations[key].buildSettings; buildSettingsObj.DEVELOPMENT_TEAM = props.ios.devTeam; buildSettingsObj.IPHONEOS_DEPLOYMENT_TARGET = props.ios.iPhoneDeploymentTarget ?? IPHONEOS_DEPLOYMENT_TARGET; buildSettingsObj.TARGETED_DEVICE_FAMILY = TARGETED_DEVICE_FAMILY; buildSettingsObj.CODE_SIGN_ENTITLEMENTS = `${nseConfig.targetName}/${nseConfig.targetName}.entitlements`; buildSettingsObj.CODE_SIGN_STYLE = "Automatic"; // Add Swift version for Swift projects if (isSwift) { buildSettingsObj.SWIFT_VERSION = props.ios.swiftVersion ?? "5.0"; } } } // Add development teams to both your target and the original project xcodeProject.addTargetAttribute( "DevelopmentTeam", props.ios.devTeam, nseTarget ); xcodeProject.addTargetAttribute("DevelopmentTeam", props.ios.devTeam); } return newConfig; }); }; const modifyPodfileForNSE: ConfigPlugin = (config) => { return withDangerousMod(config, [ 'ios', async (config) => { const iosRoot = path.join(config.modRequest.projectRoot, 'ios'); const projectName = config.name || 'YourProject'; // Detect if project is Swift or Objective-C const isSwift = await Helper.Ios.isSwiftProject(iosRoot, projectName); const nseConfig = isSwift ? SWIFT_NSE : NSE; try { const podfile = await FileManager.readFile(`${iosRoot}/Podfile`); const matches = podfile.match(nseConfig.podFileRegex); if (!matches) { fs.appendFile(`${iosRoot}/Podfile`, nseConfig.podFileSnippet, (err) => { if (err) { console.error("Error writing to Podfile"); } }); } } catch (err) { // Handle error console.error('Error reading or writing to Podfile', err); } return config; }, ]); }; const modifyPodfileForNCE: ConfigPlugin = (config) => { return withDangerousMod(config, [ 'ios', async (config) => { const iosRoot = path.join(config.modRequest.projectRoot, 'ios'); const projectName = config.name || 'YourProject'; // Detect if project is Swift or Objective-C const isSwift = await Helper.Ios.isSwiftProject(iosRoot, projectName); const nceConfig = isSwift ? SWIFT_NCE : NCE; try { const podfile = await FileManager.readFile(`${iosRoot}/Podfile`); const matches = podfile.match(nceConfig.podFileRegex); if (!matches) { fs.appendFile(`${iosRoot}/Podfile`, nceConfig.podFileSnippet, (err) => { if (err) { console.error("Error writing to Podfile."); } }); } } catch (err) { console.error('Error reading or writing to Podfile', err); } return config; }, ]); }; export default withPushiOS;