在 iOS 中,你可以使用 NSString 的 replaceOccurrencesOfString 方法来替换字符串中的特定内容。然后,你可以使用 NSData 的 writeToURL 方法将替换后的内容保存到指定的文件路径。\n\n以下是一个示例代码:\n\nobjc\nNSString *str = \"www.baidu.com\";\n\n// 获取文件路径\nNSURL *url = [[NSBundle mainBundle] URLForResource:\"index.b1c2c99e\" withExtension:\"js\" subdirectory:\"h5/static/js\"];\nNSString *filePath = [url path];\n\n// 读取文件内容\nNSError *error;\nNSString *fileContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];\n\nif (error) {\n // 处理读取文件错误\n NSLog(@"读取文件错误:\", error.localizedDescription);\n} else {\n // 替换内容\n NSString *newContent = [fileContent stringByReplacingOccurrencesOfString:\"localhost.com\" withString:str];\n\n // 保存到文件\n NSData *newData = [newContent dataUsingEncoding:NSUTF8StringEncoding];\n BOOL success = [newData writeToFile:filePath atomically:YES];\n\n if (success) {\n NSLog(@"保存成功\");\n } else {\n NSLog(@"保存失败\");\n }\n}\n\n\n注意:由于 iOS 应用程序的资源文件(包括 NSBundle mainBundle 中的文件)是只读的,所以你不能直接修改它们。上述代码中,我们先将文件内容读取到内存中进行修改,然后再将修改后的内容写入到同一文件路径中,实现替换并保存的效果。


原文地址: https://www.cveoy.top/t/topic/qbvF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录