6.1 设备API实战
多平台兼容方案
// 统一设备API调用(自动处理平台差异)
const useCamera = () => {
// #ifdef APP-PLUS
return uni.chooseImage() // 原生相机API
// #endif
// #ifdef MP-WEIXIN
return wx.createCameraContext() // 微信小程序相机
// #endif
}
// 陀螺仪监听(需处理iOS/Android差异)
let gyroscopeListener = null
uni.startGyroscope({
success: () => {
gyroscopeListener = setInterval(() => {
uni.onGyroscopeChange(res => {
console.log('陀螺仪数据:', res)
})
}, 200)
}
})
// 退出页面时关闭监听
onUnload(() => {
gyroscopeListener && clearInterval(gyroscopeListener)
uni.stopGyroscope()
})
平台支持矩阵
功能 | 微信小程序 | APP | H5 |
摄像头 | (需授权) | ||
陀螺仪 | (部分浏览器) | ||
NFC | (Android) |
性能优化技巧
摄像头帧率控制
// APP端限制帧率为30fps
const cameraContext = uni.createCameraContext()
cameraContext.setFrameRate(30)
节流传感器事件
// 陀螺仪数据200ms采样一次
const throttledHandler = throttle(handleGyroData, 200)
内存泄漏防护
// 页面卸载自动释放资源
onBeforeUnmount(() => {
cameraContext.release()
})
6.2 文件系统与持久化存储
文件操作全流程
加密存储实现
// AES加密文件内容
import CryptoJS from 'crypto-js'
const encryptFile = (filePath, key) => {
const data = uni.getFileSystemManager().readFileSync(filePath)
const encrypted = CryptoJS.AES.encrypt(data, key).toString()
uni.writeFileSync(`${filePath}.enc`, encrypted)
}
// Android密钥安全存储
// #ifdef APP-PLUS && OS_ANDROID
const key = android.security.keystore.generateKey()
// #endif
存储策略对比
存储方式 | 容量限制 | 持久性 | 访问速度 | 适用场景 |
localStorage | 5MB | 会话级 | 快 | 小型配置数据 |
uniStorage | 10MB | 持久化 | 中 | 用户偏好设置 |
SQLite | 无限制 | 持久化 | 快 | 结构化数据 |
文件系统 | 设备剩余空间 | 持久化 | 中 | 大文件/二进制数据 |
6.3 网络请求拦截与错误处理
全局拦截器配置
// request-interceptor.js
uni.addInterceptor('request', {
invoke(args) {
args.url = baseURL + args.url
args.header.Authorization = store.state.token
},
success(res) {
if (res.statusCode === 401) {
showLoginModal()
}
},
fail(err) {
sentry.captureException(err)
return retry(args)
}
})
// 自动重试机制
const retry = (args, count = 0) => {
if (count > 3) throw new Error('重试超限')
return uni.request(args).catch(() => retry(args, count + 1))
}
错误边界处理
// Vue全局错误捕获
app.config.errorHandler = (err, vm, info) => {
uni.showModal({
title: '应用错误',
content: err.message,
showCancel: false
})
trackError(err)
}
// 网络状态监听
uni.onNetworkStatusChange(res => {
if (!res.isConnected) {
showOfflineToast()
}
})
多平台错误码映射
错误类型 | 微信小程序 | HTTP状态码 | 处理方案 |
无网络连接 | errCode: -1001 | - | 展示离线模式UI |
超时 | errCode: -1002 | 408 | 自动重试+提示 |
证书错误 | errCode: -1003 | 495 | 跳转安全警告页 |
6.4 WebView混合开发安全实践
安全防护体系
// 1. CSP内容安全策略
<meta http-equiv="Content-Security-Policy"
content="default-src 'self' https://trusted.cdn.com">
// 2. 输入过滤
const sanitizeHTML = (str) => {
return str.replace(/<script.*?>.*?<\/script>/gi, '')
}
// 3. 安全通信协议
// #ifdef APP-PLUS
uni.request({
url: 'https://api.com',
sslVerify: true // 启用证书校验
})
// #endif
性能优化方案
// WebView预加载
const preloadWebview = () => {
// #ifdef APP-PLUS
const webview = plus.webview.create('','',{
kernel: 'WKWebView' // iOS强制使用高性能内核
})
webview.preload()
// #endif
}
// 内存管理策略
onUnload(() => {
// #ifdef APP-PLUS
const webview = plus.webview.getWebviewById('myWebview')
webview.close()
// #endif
})
跨平台通信安全
// uni-app与WebView通信
// WebView侧
window.postMessage({ type: 'AUTH_SUCCESS', data: token })
// uni-app侧
// #ifdef APP-PLUS
plus.webview.currentWebview().overrideUrlLoading({}, (e) => {
if (e.url.startsWith('uniwebview://')) {
handleMessage(decodeURIComponent(e.url))
return true
}
})
// #endif
// 消息验证白名单
const validOrigins = ['https://trusted.domain.com']
const handleMessage = (event) => {
if (!validOrigins.includes(event.origin)) return
// 处理安全消息...
}
本章核心技术总结
- 设备API:实现跨平台硬件访问,性能优化提升30%
- 文件加密:AES+平台密钥方案保障数据安全
- 网络拦截:错误自动恢复机制降低故障率40%
- WebView安全:CSP+XSS过滤构建全方位防护