Ionic3 iOS拍照后崩溃:NSURLConnection错误与不安全URL警告
解决Ionic 3 + Tesseract OCR在iOS上的拍照识别崩溃问题
看起来你遇到的核心问题是iOS的assets-library://协议URL不被Angular安全机制和Tesseract引擎兼容,导致了URL安全警告和NSURLConnection错误(-1002对应NSURLErrorUnsupportedURL,表示不支持该URL协议),最终引发应用崩溃。下面是具体的分析和解决方案:
问题根源
- Angular的
DomSanitizer会把assets-library://这类非标准HTTP/HTTPS的URL标记为不安全,自动拦截并发出警告,导致图片资源无法正常被Tesseract读取。 - iOS原生的NSURLConnection(Tesseract内部可能依赖类似机制加载图片)不支持直接处理
assets-library://协议的资源请求,因此抛出-1002错误。
解决方案一:改用Base64格式传递图片(最直接)
修改相机配置,直接获取Base64编码的图片数据,这样既绕过Angular的安全检查,也能被Tesseract直接识别:
步骤1:修改takePicture方法
takePicture() { let loader = this.loadingCtrl.create({ content: 'Please wait...' }); loader.present(); this.camera.getPicture({ quality: 100, destinationType: this.camera.DestinationType.DATA_URL, // 改为DATA_URL encodingType: this.camera.EncodingType.JPEG, targetHeight: 1000, sourceType: this.camera.PictureSourceType.CAMERA, // 用常量更清晰 allowEdit: true, saveToPhotoAlbum: true, correctOrientation: true }).then((imageData) => { loader.dismissAll(); // 转换为Base64图片URL this.image = `data:image/jpeg;base64,${imageData}`; this.debugText = this.image; }, (err) => { console.error(`Camera Error: ${JSON.stringify(err)}`); loader.dismissAll(); }); }
步骤2:确保analyze方法兼容Base64
你的analyze方法可以直接接收这个Base64 URL,Tesseract完全支持加载Base64格式的图片:
analyze(imageSrc: string, isDemo: boolean) { this._zone.run(() => { this.debugText = "Starting OCR..."; }); Tesseract.recognize(imageSrc) .progress(message => { this._zone.run(() => { this.debugText = `Progress: ${message.status} ${(message.progress * 100).toFixed(0)}%`; }); }) .then(result => { this._zone.run(() => { this.recognizedText = result.text; this.debugText = "OCR Completed!"; }); }) .catch(err => { this._zone.run(() => { this.debugText = `OCR Failed: ${err}`; }); }); }
解决方案二:保留本地URI并绕过安全检查(如果需要保留相册存储)
如果你必须使用NATIVE_URI(比如要保留图片到相册),需要两步处理:
- 用Angular的
DomSanitizer标记URL为安全资源 - 把
assets-library://转换为Tesseract能读取的格式(比如通过cordova-plugin-file转Base64)
步骤1:引入并注入DomSanitizer
// 在home.ts顶部导入 import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'; // 在constructor中注入 constructor( private camera: Camera, public navCtrl: NavController, public platform: Platform, public loadingCtrl: LoadingController, public actionsheetCtrl: ActionSheetController, private sanitizer: DomSanitizer // 添加这一行 ) { this._zone = new NgZone({ enableLongStackTrace: false }); }
步骤2:修改takePicture方法处理URI
// 先安装cordova-plugin-file: // ionic cordova plugin add cordova-plugin-file // npm install @ionic-native/file // 导入File模块 import { File } from '@ionic-native/file'; // 在constructor中注入File constructor(..., private file: File) { ... } // 修改takePicture takePicture() { let loader = this.loadingCtrl.create({ content: 'Please wait...' }); loader.present(); this.camera.getPicture({ quality: 100, destinationType: this.camera.DestinationType.NATIVE_URI, encodingType: this.camera.EncodingType.JPEG, targetHeight: 1000, sourceType: this.camera.PictureSourceType.CAMERA, allowEdit: true, saveToPhotoAlbum: true, correctOrientation: true }).then((imageURI) => { loader.dismissAll(); // 标记URL为安全资源,避免Angular sanitize警告 this.image = this.sanitizer.bypassSecurityTrustResourceUrl(imageURI) as string; this.debugText = imageURI; // 转换assets-library URI为Base64(供Tesseract使用) this.file.resolveLocalFilesystemUrl(imageURI).then(fileEntry => { fileEntry.file(file => { const reader = new FileReader(); reader.onloadend = () => { const base64Image = reader.result as string; // 这里可以直接调用analyze,或者存储base64供后续使用 // this.analyze(base64Image, false); }; reader.readAsDataURL(file); }); }).catch(err => { console.error('File Resolve Error:', err); }); }, (err) => { console.error(`Camera Error: ${JSON.stringify(err)}`); loader.dismissAll(); }); }
额外注意事项
- iOS权限配置:确保在
Info.plist中添加相机和相册权限描述,否则iOS会直接阻止应用访问:
<key>NSCameraUsageDescription</key> <string>需要访问相机进行拍照识别</string> <key>NSPhotoLibraryUsageDescription</key> <string>需要访问相册选择图片进行识别</string>
- Tesseract语言包:如果需要识别中文等非英文内容,确保在Tesseract初始化时加载对应语言包,避免识别结果为空。
- NgZone使用:Tesseract的回调运行在Angular的Zone之外,必须用
this._zone.run()包裹UI更新代码,确保视图能实时刷新。
内容的提问来源于stack exchange,提问作者mm1975
相关产品推荐
相关产品推荐

