Ionic3(iOS)报错:Not allowed to load local resource问题求助
Ah, I’ve run into this exact issue before! The problem boils down to iOS’s WKWebView security restrictions—it blocks direct access to file:// URLs from the web context, which is why your code works smoothly on Android but throws that error on iOS. Here are two reliable solutions to get things working:
Solution 1: Use Base64 Data URL (Simplest Approach)
Instead of requesting a file URI from the camera plugin, ask it to return a base64-encoded string of the image. This works seamlessly across both platforms without needing extra plugins.
Modify your camera options to switch the destination type:
let cameraOptions = { quality: 50, destinationType: this.camera.DestinationType.DATA_URL, // Updated this line encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE }; this.camera.getPicture(cameraOptions).then((imageData) => { // Add the data URI prefix to display the image in an <img> tag this.myImage = `data:image/jpeg;base64,${imageData}`; });
Note: Base64 strings are roughly 33% larger than the original file, so keeping your quality setting at 50 (like you already have) helps avoid performance issues with large images.
Solution 2: Convert File URI to a Web-Friendly Path (Better for Large Images)
If you’d rather work with actual files instead of base64 (to save memory), use the Cordova File plugin to convert the local file URI into a URL that WKWebView can safely load.
- First, install the File plugin if you haven’t already:
cordova plugin add cordova-plugin-file
- Update your code to resolve the file URI and generate a usable URL:
let cameraOptions = { quality: 50, destinationType: this.camera.DestinationType.FILE_URI, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE }; this.camera.getPicture(cameraOptions).then((imageData) => { // Resolve the local file URI to a file entry window.resolveLocalFileSystemURL(imageData, (fileEntry) => { // Create a web-accessible URL for the file this.myImage = fileEntry.toURL(); }, (error) => { console.error('Error resolving file URI:', error); }); });
This method keeps the image as a local file but generates a secure URL that iOS allows loading in the web view.
Either of these approaches should fix the error on iOS while keeping your Android functionality intact.
内容的提问来源于stack exchange,提问作者Mohan Gopi

