Commit c72aa873 by liimin

refactor: 重构上传服务与录音管理初始化逻辑

- 将 RecordService 初始化移至构造函数,移除组件中的手动调用
- 优化 Webview 获取逻辑,增强健壮性与自动恢复能力
- 简化上传服务错误处理与任务调度,移除冗余黑名单检查
- 采用事件驱动方式初始化上传 Webview,提升可靠性
- 清理调试日志与无用代码,提升代码可维护性
1 parent 45724665
...@@ -105,9 +105,6 @@ export default { ...@@ -105,9 +105,6 @@ export default {
this.userInfo = userInfo this.userInfo = userInfo
this.currentType = uni.$storage.get('typeItem') this.currentType = uni.$storage.get('typeItem')
// if (this.checkRecordAudio) permision.requestAndroidPermission('android.permission.RECORD_AUDIO') // 进入界面时检查权限 // if (this.checkRecordAudio) permision.requestAndroidPermission('android.permission.RECORD_AUDIO') // 进入界面时检查权限
// 初始化上传相关逻辑
this.initUploader()
}, },
provide() { provide() {
return { return {
...@@ -163,27 +160,22 @@ export default { ...@@ -163,27 +160,22 @@ export default {
this.$emit('changeType') this.$emit('changeType')
}, },
handleUploadMessage(event) { handleUploadMessage(event) {
// 接收来自 Webview 的消息,并转发给 UploadService // 接收来自 Webview 的消息
const data = event.detail.data[0] const data = event.detail.data[0]
if (data) { if (data) {
// 构造 Service 需要的格式 { detail: { data: [payload] } } // 1. 处理 Webview 就绪信号 (Event-Driven 初始化)
// 或者直接让 Service 接收 payload if (data.action === 'webview_ready') {
// 目前 Service.handlerMessage 期望的是 { detail: { data: [...] } } uni.$logger.local.info('【上传服务】收到 Webview 就绪信号,开始注入 Context')
UploadService.handlerMessage(event) // 此时 Webview 必然已存在,无需延迟
}
},
initUploader() {
// 初始化上传服务 (移除 init 调用,交由 App.vue 统一管理)
// UploadService.init()
// 注入 Webview 实例
this.injectWebview()
},
injectWebview() {
// 恢复:通过 $refs 获取模板中声明的 Webview 实例
// 注意:需要等待 mounted 后一段时间确保 webview 已经渲染
this.$nextTick(() => { this.$nextTick(() => {
UploadService.setWebviewContext(this.$refs.uploaderWebview, this) UploadService.setWebviewContext(this.$refs.uploaderWebview, this)
}) })
return
} else {
// 2. 正常的文件上传回调
UploadService.handlerMessage(event)
}
}
}, },
handleTouchStart() { handleTouchStart() {
uni.$emit('reset_timeout') uni.$emit('reset_timeout')
......
...@@ -47,6 +47,14 @@ ...@@ -47,6 +47,14 @@
<script src="js/OSSUpLoader.js"></script> <script src="js/OSSUpLoader.js"></script>
<script> <script>
// document.addEventListener('UniAppJSBridgeReady', function(){ // document.addEventListener('UniAppJSBridgeReady', function(){
document.addEventListener('UniAppJSBridgeReady', function() {
// 主动告知宿主环境,Webview 已准备就绪
uni.postMessage({
data: {
action: 'webview_ready'
}
});
});
/** /**
* 该函数用于接收来自 UniApp 的消息,它包含了文件上传所需的所有信息 * 该函数用于接收来自 UniApp 的消息,它包含了文件上传所需的所有信息
* @param {string} accessKeyId - OSS 访问密钥 ID * @param {string} accessKeyId - OSS 访问密钥 ID
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* @Author: 前端 qianduan01@didihu.com.cn * @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-12-26 10:03:54 * @Date: 2024-12-26 10:03:54
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2026-01-21 17:13:07 * @LastEditTime: 2026-01-21 19:05:50
* @FilePath: \simgle_app\mixin\record\recorder.js * @FilePath: \simgle_app\mixin\record\recorder.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
...@@ -22,7 +22,6 @@ export default { ...@@ -22,7 +22,6 @@ export default {
}, },
async mounted() { async mounted() {
this.recordService = RecordService.getInstance() this.recordService = RecordService.getInstance()
await this.recordService.init()
}, },
methods: { methods: {
...mapMutations('audio', ['setReceptionStatus']), ...mapMutations('audio', ['setReceptionStatus']),
...@@ -127,9 +126,5 @@ export default { ...@@ -127,9 +126,5 @@ export default {
async isPermission() { async isPermission() {
return this.recordService.isPermission() return this.recordService.isPermission()
} }
},
beforeDestroy() {
this.recordService?.destroy()
this.recordService = null
} }
} }
...@@ -14,7 +14,7 @@ class RecordService { ...@@ -14,7 +14,7 @@ class RecordService {
this._startAudioPromise = null this._startAudioPromise = null
this.timeoutService = null this.timeoutService = null
// 初始化 // 初始化
// this.init() // 不在构造函数中自动初始化,留给外部调用或 getInstance this.init()
} }
static getInstance() { static getInstance() {
......
...@@ -4,8 +4,8 @@ ...@@ -4,8 +4,8 @@
* @Author: limin * @Author: limin
* @Date: 2024-12-06 10:13:02 * @Date: 2024-12-06 10:13:02
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2026-01-21 17:02:23 * @LastEditTime: 2026-01-21 18:21:56
* @FilePath: \gl_tape\utils\recordManager\TimeoutService.js * @FilePath: \simgle_app\utils\recordManager\TimeoutService.js
*/ */
class TimeoutService { class TimeoutService {
TIMEOUT = 40 // 40分钟 TIMEOUT = 40 // 40分钟
...@@ -62,7 +62,6 @@ class TimeoutService { ...@@ -62,7 +62,6 @@ class TimeoutService {
//实现防抖 //实现防抖
if (this._debounceTimer) clearTimeout(this._debounceTimer) if (this._debounceTimer) clearTimeout(this._debounceTimer)
this._debounceTimer = setTimeout(() => { this._debounceTimer = setTimeout(() => {
console.log("🚀 ~ TimeoutService ~ handleTouchStart ~ this._debounceTimer:")
this._lastActiveTime = Date.now() this._lastActiveTime = Date.now()
}, 1000) }, 1000)
} }
......
...@@ -53,10 +53,24 @@ class UploadService { ...@@ -53,10 +53,24 @@ class UploadService {
} }
/** /**
* 设置 Webview 实例(由 UI 组件注入) * 内部方法:设置并激活 Webview
* @param {Object} webviewComponent - Vue 组件引用 ($refs.uploaderWebview) * @param {Object} wv - 原生 Webview 对象
* @param {Object} vueContext - Vue 实例上下文 (this) * @param {Object} refInfo - 引用信息 { component, context }
* @returns {boolean} 是否设置成功
*/ */
_setupWebview(wv, refInfo) {
if (wv) {
if (typeof wv.setStyle === 'function') {
wv.setStyle({ top: '-1000px', left: '-1000px', width: '10px', height: '10px' })
}
this.wv = wv
if (refInfo) {
this._webviewRef = refInfo
}
return true
}
return false
}
/** /**
* 设置 Webview 实例(由 UI 组件注入) * 设置 Webview 实例(由 UI 组件注入)
* @param {Object} webviewComponent - Vue 组件引用 ($refs.uploaderWebview) * @param {Object} webviewComponent - Vue 组件引用 ($refs.uploaderWebview)
...@@ -67,21 +81,18 @@ class UploadService { ...@@ -67,21 +81,18 @@ class UploadService {
// 尝试获取实例,带有重试机制 (封装在 getWebviewInstance 中) // 尝试获取实例,带有重试机制 (封装在 getWebviewInstance 中)
const wv = await getWebviewInstance(webviewComponent, vueContext) const wv = await getWebviewInstance(webviewComponent, vueContext)
// 无论成功与否,都保存引用以便后续轮询中自动恢复 // 保存引用以便后续轮询中自动恢复
this._webviewRef = { component: webviewComponent, context: vueContext } const refInfo = { component: webviewComponent, context: vueContext }
if (wv) { if (this._setupWebview(wv, refInfo)) {
uni.$logger.local.info('【上传服务】Webview Context 已注入') uni.$logger.local.info('【上传服务】Webview Context 已注入')
if (typeof wv.setStyle === 'function') {
wv.setStyle({ top: '-1000px', left: '-1000px', width: '10px', height: '10px' })
}
this.wv = wv
// Webview 就绪,正式启动轮询 // Webview 就绪,正式启动轮询
if (!this._pumpRunning) { if (!this._pumpRunning) {
this.startPolling() this.startPolling()
} }
} else { } else {
// 即使第一次没成功,也保存引用,以便后续自动恢复
this._webviewRef = refInfo
uni.$logger.local.warn('【上传服务】Webview 初始化未就绪,将在轮询中自动恢复') uni.$logger.local.warn('【上传服务】Webview 初始化未就绪,将在轮询中自动恢复')
} }
// #endif // #endif
...@@ -145,7 +156,6 @@ class UploadService { ...@@ -145,7 +156,6 @@ class UploadService {
} }
parseFileInfo(data) { parseFileInfo(data) {
try {
/// 1. 尝试从 Webview 回调结构中提取 payload /// 1. 尝试从 Webview 回调结构中提取 payload
const payload = data?.detail?.data?.[0] const payload = data?.detail?.data?.[0]
...@@ -162,12 +172,7 @@ class UploadService { ...@@ -162,12 +172,7 @@ class UploadService {
if (data && (data.status === FileStatus.NoFile || data.status === FileStatus.NotExist)) { if (data && (data.status === FileStatus.NoFile || data.status === FileStatus.NotExist)) {
return this._parseNoFileStatus(data) return this._parseNoFileStatus(data)
} }
return null return null
} catch (error) {
uni.$logger.local.error(`【上传服务】 == 解析文件信息异常: ${error.message}`)
return null
}
} }
_parseNoFileStatus(data) { _parseNoFileStatus(data) {
...@@ -223,7 +228,6 @@ class UploadService { ...@@ -223,7 +228,6 @@ class UploadService {
} }
_changeFilePathToServer(record, fileInfo) { _changeFilePathToServer(record, fileInfo) {
try {
const _record = deepClone(record) const _record = deepClone(record)
uni.$logger.local.info(`【上传服务】 == 开始更新文件路径, recordId: ${_record.id}`) uni.$logger.local.info(`【上传服务】 == 开始更新文件路径, recordId: ${_record.id}`)
...@@ -244,10 +248,6 @@ class UploadService { ...@@ -244,10 +248,6 @@ class UploadService {
uni.$logger.local.warn(`【上传服务】 == 未找到匹配的文件记录: ${JSON.stringify(fileInfo)}`) uni.$logger.local.warn(`【上传服务】 == 未找到匹配的文件记录: ${JSON.stringify(fileInfo)}`)
} }
return _record return _record
} catch (error) {
uni.$logger.error(`【上传服务】 == 修改文件路径失败: ${error.message}`)
throw new Error('【上传服务】 == 修改文件路径失败!!')
}
} }
_isTargetFile(item, fileInfo) { _isTargetFile(item, fileInfo) {
...@@ -307,19 +307,11 @@ class UploadService { ...@@ -307,19 +307,11 @@ class UploadService {
} }
async uploadRecord(record) { async uploadRecord(record) {
// 任务开始前,再次检查黑名单(防止队列滞后)
const taskKey = this._getTaskKey(record.recordId, record.fileName)
if (this._isInBlackList(taskKey)) {
uni.$logger.local.warn(`【上传服务】 == 任务在黑名单中,跳过: ${taskKey}`)
this.endTask()
return
}
uni.$logger.local.info(`【上传服务】 == 开始上传文件!! record: ${JSON.stringify(record)}`) uni.$logger.local.info(`【上传服务】 == 开始上传文件!! record: ${JSON.stringify(record)}`)
if (record.status === FileStatus.NoFile || record.status === FileStatus.NotExist) { if (record.status === FileStatus.NoFile || record.status === FileStatus.NotExist) {
uni.$logger.local.info(`【上传服务】 == 记录中有未上传文件,或文件不存在, 直接保存记录!!`) uni.$logger.local.info(`【上传服务】 == 记录中有未上传文件,或文件不存在, 直接保存记录!!`)
this.save(record) this.save(record)
} else { } else {
try {
const token = await uni.$api.commonApi.getOSSToken({}) const token = await uni.$api.commonApi.getOSSToken({})
let { secretKey: lsaccessKeySecret, securityToken = '', secretId: lsaccessKeyId, bucketName, region } = token || {} let { secretKey: lsaccessKeySecret, securityToken = '', secretId: lsaccessKeyId, bucketName, region } = token || {}
bucketName = await this._tryDecrypt(bucketName, 'Bucket') bucketName = await this._tryDecrypt(bucketName, 'Bucket')
...@@ -327,16 +319,10 @@ class UploadService { ...@@ -327,16 +319,10 @@ class UploadService {
lsaccessKeySecret = await this._tryDecrypt(lsaccessKeySecret, 'AccessKeySecret') lsaccessKeySecret = await this._tryDecrypt(lsaccessKeySecret, 'AccessKeySecret')
lsaccessKeyId = await this._tryDecrypt(lsaccessKeyId, 'AccessKeyId') lsaccessKeyId = await this._tryDecrypt(lsaccessKeyId, 'AccessKeyId')
this._safeEvalUpload(lsaccessKeyId, lsaccessKeySecret, securityToken, record.fileName, record.filePath, record.recordId, bucketName, region) this._safeEvalUpload(lsaccessKeyId, lsaccessKeySecret, securityToken, record.fileName, record.filePath, record.recordId, bucketName, region)
} catch (error) {
this.reportError(`上传文件时发生异常(uploadRecord): ${error.message}`)
this.endTask()
throw error
}
} }
} }
async _tryDecrypt(str, label) { async _tryDecrypt(str, label) {
try {
if (str && (str.includes('=') || str.length > 50)) { if (str && (str.includes('=') || str.length > 50)) {
let decrypted = await decryptAES(str) let decrypted = await decryptAES(str)
if (decrypted) { if (decrypted) {
...@@ -346,9 +332,6 @@ class UploadService { ...@@ -346,9 +332,6 @@ class UploadService {
} }
return decrypted return decrypted
} }
} catch (e) {
uni.$logger.error(`${label} decryption error` + e.message)
}
return str return str
} }
...@@ -381,7 +364,6 @@ class UploadService { ...@@ -381,7 +364,6 @@ class UploadService {
async _saveOrUpdate(data) { async _saveOrUpdate(data) {
uni.$logger.local.info(`【上传服务】 == 开始保存或更新接待记录!!`) uni.$logger.local.info(`【上传服务】 == 开始保存或更新接待记录!!`)
try {
const { status, tempFilePath, receptionStatus, ...record } = data const { status, tempFilePath, receptionStatus, ...record } = data
const fileList = Array.isArray(record.urlList) ? record.urlList : [] const fileList = Array.isArray(record.urlList) ? record.urlList : []
const isAllCompleted = status === FileStatus.NoFile || fileList.every(i => [FileStatus.Uploaded, FileStatus.Completed].includes(i.status)) const isAllCompleted = status === FileStatus.NoFile || fileList.every(i => [FileStatus.Uploaded, FileStatus.Completed].includes(i.status))
...@@ -390,10 +372,6 @@ class UploadService { ...@@ -390,10 +372,6 @@ class UploadService {
} else { } else {
await this._handleIncompleteRecord(record) await this._handleIncompleteRecord(record)
} }
} catch (error) {
uni.$logger.error(`【上传服务】 == 上传接待记录异常,error:${error.message}`)
this._addToBlackList(this._currentKey, `Upload record failed: ${JSON.stringify(error.message)}`)
}
} }
async _handleCompletedRecord(record, fileList) { async _handleCompletedRecord(record, fileList) {
...@@ -469,9 +447,9 @@ class UploadService { ...@@ -469,9 +447,9 @@ class UploadService {
try { try {
for (const cur of records) { for (const cur of records) {
// 1. 记录级别的黑名单检查 (针对空文件等整条记录的问题) // 1. 记录级别的黑名单检查 (针对空文件等整条记录的问题)
if (this._isInBlackList(cur.id)) { // if (this._isInBlackList(cur.id)) {
continue // continue
} // }
const urlList = this.urlListFilter(cur.urlList) const urlList = this.urlListFilter(cur.urlList)
if (urlList.length == 0) { if (urlList.length == 0) {
result.push({ status: FileStatus.NoFile, recordId: cur.id }) result.push({ status: FileStatus.NoFile, recordId: cur.id })
...@@ -488,10 +466,10 @@ class UploadService { ...@@ -488,10 +466,10 @@ class UploadService {
const filePath = aFullPath.join('/') + '/' const filePath = aFullPath.join('/') + '/'
// 2. 文件任务级别的黑名单检查 // 2. 文件任务级别的黑名单检查
const taskKey = this._getTaskKey(cur.id, fileName) // const taskKey = this._getTaskKey(cur.id, fileName)
if (this._isInBlackList(taskKey)) { // if (this._isInBlackList(taskKey)) {
continue // continue
} // }
const file2Up = { ...file, recordId: cur.id, fileName, filePath } const file2Up = { ...file, recordId: cur.id, fileName, filePath }
const fileExists = await this.checkFileExists(file.file) const fileExists = await this.checkFileExists(file.file)
if (!fileExists) { if (!fileExists) {
...@@ -558,17 +536,26 @@ class UploadService { ...@@ -558,17 +536,26 @@ class UploadService {
} }
task(record) { task(record) {
return new Promise(resolve => { return new Promise(async resolve => {
const timeoutId = this._startWatchdog() const timeoutId = this._startWatchdog()
this.updateResolve = () => { this.updateResolve = () => {
clearTimeout(timeoutId) clearTimeout(timeoutId)
resolve() resolve()
} }
this._taskStartTime = Date.now() this._taskStartTime = Date.now()
this._currentKey = this._getTaskKey(record.recordId, record.fileName) this._currentKey = this._getTaskKey(record.recordId, record.fileName)
this.uploadRecord(record) try {
if (this._isInBlackList(this._currentKey)) {
uni.$logger.local.warn(`【上传服务】 == 任务在黑名单中,跳过: ${taskKey}`)
this.endTask()
return
}
await this.uploadRecord(record)
} catch (error) {
this._addToBlackList(this._currentKey, `上传文件时发生异常(uploadRecord): ${error.message}`)
this.reportError(`上传文件时发生异常(uploadRecord): ${error.message}`, error.message)
this.endTask()
}
}) })
} }
...@@ -627,7 +614,7 @@ class UploadService { ...@@ -627,7 +614,7 @@ class UploadService {
this._pumpTimer = setTimeout(() => { this._pumpTimer = setTimeout(() => {
this._schedulerPump() this._schedulerPump()
}, 0) }, 0)
uni.$logger.local.info(`【上传服务】 =========开始轮询========`) uni.$logger.local.info(`【上传服务】 =========开启上传服务========`)
} }
canclePromises() { canclePromises() {
...@@ -639,22 +626,14 @@ class UploadService { ...@@ -639,22 +626,14 @@ class UploadService {
* @returns {Promise<boolean>} 是否恢复成功 * @returns {Promise<boolean>} 是否恢复成功
*/ */
async _tryRecoverWebview() { async _tryRecoverWebview() {
uni.$logger.local.warn('【上传服务】 == WebView未就绪,等待注入或自动恢复...')
// 尝试自动恢复 // 尝试自动恢复
if (this._webviewRef && this._webviewRef.component) { if (this._webviewRef && this._webviewRef.component) {
const wv = await getWebviewInstance(this._webviewRef.component, this._webviewRef.context) const wv = await getWebviewInstance(this._webviewRef.component, this._webviewRef.context)
if (wv) { if (this._setupWebview(wv)) {
if (typeof wv.setStyle === 'function') {
wv.setStyle({ top: '-1000px', left: '-1000px', width: '10px', height: '10px' })
}
this.wv = wv
uni.$logger.local.info('【上传服务】 == WebView 自动恢复成功!') uni.$logger.local.info('【上传服务】 == WebView 自动恢复成功!')
return true return true
} }
} }
uni.$logger.local.warn('【上传服务】 == WebView 仍未就绪,跳过本次轮询')
return false return false
} }
...@@ -662,20 +641,9 @@ class UploadService { ...@@ -662,20 +641,9 @@ class UploadService {
if (this._pumpRunning) return if (this._pumpRunning) return
this._pumpRunning = true this._pumpRunning = true
try { try {
// 关键:等待 Webview 就绪
// 如果 Webview 还没注入,这里会一直挂起,直到 setWebviewContext 成功调用 _resolveWebviewReady
// 如果第一次初始化失败,我们依靠轮询中的自动恢复逻辑来重新触发 resolve
if (!this.wv) {
const isReady = await this._tryRecoverWebview()
if (!isReady) {
this.waitting()
return
}
}
const stopReason = await this._checkStopConditions() const stopReason = await this._checkStopConditions()
if (stopReason) { if (stopReason) {
uni.$logger.local.info(`【上传服务】 == ${stopReason}, 停止轮询`) uni.$logger.local.info(`【上传服务】 == ${stopReason}, 暂停上传服务 ,等待唤醒`)
return return
} }
...@@ -713,6 +681,13 @@ class UploadService { ...@@ -713,6 +681,13 @@ class UploadService {
return '网络异常,等待网络恢复' return '网络异常,等待网络恢复'
} }
if (!this.wv) {
const isReady = await this._tryRecoverWebview()
if (!isReady) {
return 'Webview未就绪'
}
}
if (this.updateResolve) { if (this.updateResolve) {
return '任务正在执行中' return '任务正在执行中'
} }
...@@ -722,7 +697,7 @@ class UploadService { ...@@ -722,7 +697,7 @@ class UploadService {
} }
if (!this.snapshot || this.snapshot.size === 0) { if (!this.snapshot || this.snapshot.size === 0) {
return '队列为空,等待新任务唤醒' return '队列为空'
} }
return null return null
} }
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* @Author: 前端 qianduan01@didihu.com.cn * @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-08 17:16:46 * @Date: 2024-04-08 17:16:46
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2026-01-21 15:02:24 * @LastEditTime: 2026-01-22 11:24:40
* @FilePath: \simgle_app\utils\utils.js * @FilePath: \simgle_app\utils\utils.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
...@@ -173,36 +173,69 @@ export function serializeIfObject(value) { ...@@ -173,36 +173,69 @@ export function serializeIfObject(value) {
} }
/** /**
* 获取 Webview 实例的工具方法 * 获取 Webview 实例 (增强版)
* @param {Object} webviewComponent - Vue 组件引用 * @param {Object} component - Vue 组件引用
* @param {Object} vueContext - Vue 实例上下文 * @param {Object} context - Vue 上下文
*/ */
export function getWebviewInstance(component, context, retries = 3, interval = 300) { export function getWebviewInstance(component, context) {
return new Promise((resolve) => { return new Promise((resolve) => {
const tryGet = (left) => { // 1. 尝试直接获取
try { if (component && typeof component.$getAppWebview === 'function') {
// 按照指定逻辑获取: 依赖父组件作用域获取原生 Webview,并取第一个子窗口 const wv = component.$getAppWebview()
const currentWebview = context?.$parent?.$scope?.$getAppWebview?.()
const wv = currentWebview?.children?.()?.[0]
if (wv) { if (wv) {
resolve(wv) resolve(wv)
return return
} }
} catch (e) {
console.warn('Webview获取异常', e)
} }
if (left > 0) { // 2. 尝试通过页面查找 (解决组件未挂载完全时的获取问题)
setTimeout(() => tryGet(left - 1), interval) const tryFind = () => {
} else { try {
resolve(null) let pageWebview = null
if (context && context.$scope && typeof context.$scope.$getAppWebview === 'function') {
pageWebview = context.$scope.$getAppWebview()
} else if (context && context.$parent && context.$parent.$scope && typeof context.$parent.$scope.$getAppWebview === 'function') {
pageWebview = context.$parent.$scope.$getAppWebview()
}
if (pageWebview && typeof pageWebview.children === 'function') {
const children = pageWebview.children()
for (let i = 0; i < children.length; i++) {
const child = children[i]
const url = child.getURL ? child.getURL() : ''
if (url && url.indexOf('hybrid/html/index.html') > -1) {
return child
}
}
}
} catch (e) {
console.warn('getWebviewInstance error:', e)
}
return null
} }
const wv = tryFind()
if (wv) {
resolve(wv)
return
} }
tryGet(retries) // 3. 异步重试 (处理渲染延迟)
let retries = 0
const timer = setInterval(() => {
retries++
const wv = tryFind()
if (wv) {
clearInterval(timer)
resolve(wv)
} else if (retries >= 10) {
clearInterval(timer)
resolve(null)
}
}, 200)
}) })
} }
export function isInteger(value) { export function isInteger(value) {
if (typeof value === 'number') { if (typeof value === 'number') {
return Number.isInteger(value) return Number.isInteger(value)
......
...@@ -3,7 +3,7 @@ export default class RecordsWorker { ...@@ -3,7 +3,7 @@ export default class RecordsWorker {
constructor() {} constructor() {}
async work(deviceId, data, ws) { async work(deviceId, data, ws) {
try { try {
const records = await uni.$dbRecord.getRecords() const records = await uni.$dbRecord.getCompletedRecords()
const msg = `记录获取成功 records -> ${JSON.stringify(records)}` const msg = `记录获取成功 records -> ${JSON.stringify(records)}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ code: 200, msg: '获取记录成功', data:records }) ws.send({ code: 200, msg: '获取记录成功', data:records })
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!