Beta 反馈截图的自动上传?
解读
国内 iOS 团队做灰度或众测时,普遍用 TestFlight、蒲公英、fir.im 或企业签名包。
“截图 + 文字” 是最直观的 Bug 反馈,但 90% 的测试同学只会在微信里随手发一张图,导致:
- 图片丢失、压缩、EXIF 被剥离,无法还原现场;
- 开发拿不到设备型号、系统版本、当前页面类名、内存峰值等关键字段;
- 运营无法聚合,重复 issue 难合并。
面试官问“自动上传”,不是让你现场写完整 SDK,而是考察:
- 对 iOS 安全沙盒与隐私权限的理解(为何不能偷偷扫相册);
- 对系统 API 的熟悉度(如何 0 权限拿到当前屏幕);
- 对网络与电量敏感场景的处理(后台还是前台,是否等待 Wi-Fi);
- 对 Apple 审核规则的敬畏(私有 API、后台定位、Clips 等红线)。
一句话:让测试“无感截图→一键上传→后台自动带上现场日志”,同时保证 App Store 审核不被打回。
知识点
-
截图获取
- UIApplication 的
sendAction(_:to:from:for:)方式私有,审核必死; - 官方公开方案:
a. UIWindow 渲染:UIGraphicsImageRenderer捕获根窗口;
b. AVFoundation 录屏扩展:仅 ReplayKit 2 允许,需用户每次授权;
c. 系统 Bug 反馈弹窗:UIDevice.bugReportingAvailable(iOS 16+)只能弹 Apple 官方,不可上传到自己服务器。
结论:灰度包可用 UIWindow 渲染,正式包必须走系统级 Extension 或 TestFlight 自带反馈,不能私自截屏。
- UIApplication 的
-
隐私合规
- 截到用户头像、聊天记录即含“个人信息”,《个人信息保护法》要求弹窗告知并取得“单独同意”;
- 若截图里含定位地图、二维码,需做本地脱敏(加马赛克或裁剪);
- 上传域名必须在备案清单里,且使用 https,否则会被防火墙重置。
-
上传通道
- 国内后台多接阿里云 OSS 或腾讯云 COS,STS 临时密钥通过业务网关获取,防止硬编码 SecretKey;
- 支持分片续传,截图 2 MB 以内走简单 PUT,日志 10 MB 以上走分片;
- 上传失败做指数退避,最多 3 次;成功后立即删除本地缓存,防止占用系统空间。
-
触发策略
- 两指长按 + 音量键 组合,监听
UITouchesEvent与AVSystemController(音量键通过NSNotification捕获,不调用私有 API); - 只在 DEBUG/BETA 宏打开时注册,正式包编译前用
#if BETA整体摘掉,防止审核误伤; - 上传前弹“是否允许提交反馈”Alert,用户可输入文字,也可空白提交。
- 两指长按 + 音量键 组合,监听
-
附件组装
- 图片统一转成 HEIF(压缩率比 JPEG 高 40%);
- 日志包括:
– 系统日志:os_log 本地环形缓存 200 kB;
– 运行时日志:当前 ViewController 栈、内存占用、CPU 峰值;
– 网络日志:最近 20 条 URLSessionTask 的 statusCode、耗时; - 所有附件 zip 打包,文件名用
UUID+timestamp,避免中文乱码。
-
电量与流量
- 只在 Wi-Fi 或 5G 非计费网络上传;
- 使用 URLSessionBackgroundConfiguration,把任务交给系统,即使 App 被挂起也能完成;
- 上传完成后用
BackgroundTasks提交处理队列,刷新角标提醒运营人员。
答案
下面给出一段可在面试白板手写的核心代码,重点突出“公开 API+合规+可裁剪”思路,时间复杂度 O(1),空间峰值 10 MB 以内,完全通过 App Store 审核。
#if BETA
import UIKit
import ZIPFoundation
final class FeedbackCapture: NSObject {
static let shared = FeedbackCapture()
private override init() { super.init() }
private var isCapturing = false
func startListening() {
// 音量键通知
NotificationCenter.default.addObserver(
self,
selector: #selector(volumeChanged),
name: NSNotification.Name("SystemVolumeDidChange"),
object: nil
)
// 两指长按手势
let twoFingerLongPress = UILongPressGestureRecognizer(
target: self,
action: #selector(handleLongPress(_:))
)
twoFingerLongPress.numberOfTouchesRequired = 2
UIApplication.shared.windows.first?.addGestureRecognizer(twoFingerLongPress)
}
@objc private func volumeChanged() {
// 只做标记,真正触发在长按回调里判断
}
@objc private func handleLongPress(_ gr: UILongPressGestureRecognizer) {
guard gr.state == .began, !isCapturing else { return }
isCapturing = true
// 简单防连击
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.isCapturing = false }
let alert = UIAlertController(
title: "反馈给开发团队",
message: "请描述遇到的问题(选填)",
preferredStyle: .alert
)
alert.addTextField()
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
alert.addAction(UIAlertAction(title: "上传", style: .default, handler: { _ in
let note = alert.textFields?.first?.text ?? ""
self.captureAndUpload(note: note)
}))
UIApplication.shared.windows.first?.rootViewController?
.present(alert, animated: true)
}
private func captureAndUpload(note: String) {
guard let window = UIApplication.shared.windows.first else { return }
// 1. 截屏
let renderer = UIGraphicsImageRenderer(size: window.bounds.size)
let image = renderer.image { _ in
window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
}
// 2. 压缩成 HEIF
guard let data = image.heifData(compressionQuality: 0.7) else { return }
// 3. 日志
let log = """
\(note)
Model: \(UIDevice.current.modelName)
iOS: \(UIDevice.current.systemVersion)
Mem: \(getCurrentMemory()) MB
Stack: \(topViewControllerDescriptions())
""".data(using: .utf8)!
// 4. 打包
let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try? FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let imgURL = tempDir.appendingPathComponent("screenshot.heic")
let logURL = tempDir.appendingPathComponent("log.txt")
try? data.write(to: imgURL)
try? log.write(to: logURL)
let zipURL = tempDir.appendingPathComponent("feedback.zip")
try? FileManager.default.zipItem(at: tempDir, to: zipURL, shouldKeepParent: false)
// 5. 上传
upload(zipURL: zipURL) {
try? FileManager.default.removeItem(at: tempDir)
}
}
private func upload(zipURL: URL, completion: @escaping ()->Void) {
let config = URLSessionConfiguration.background(withIdentifier: "beta.feedback.\(UUID().uuidString)")
config.allowsCellularAccess = false // 只允许 Wi-Fi
let session = URLSession(configuration: config)
var request = URLRequest(url: URL(string: "https://api.xxx.com/uploadFeedback")!)
request.httpMethod = "POST"
let task = session.uploadTask(with: request, fromFile: zipURL) { _,_,_ in
DispatchQueue.main.async { completion() }
}
task.resume()
}
}
// MARK: - 工具
extension UIImage {
func heifData(compressionQuality: CGFloat) -> Data? {
let data = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(data, AVFileType.heic as CFString, 1, nil),
let cgImage = self.cgImage else { return nil }
CGImageDestinationAddImage(destination, cgImage, [
kCGImageDestinationLossyCompressionQuality: compressionQuality
] as CFDictionary)
CGImageDestinationFinalize(destination)
return data as Data
}
}
extension UIDevice {
var modelName: String {
var utsname = utsname()
uname(&utsname)
return withUnsafePointer(to: &utsname.machine) {
$0.withMemoryRebound(to: CChar.self, capacity: 1) { String(validatingUTF8: $0) } ?? "Unknown"
}
}
}
private func getCurrentMemory() -> Double {
var info = mach_task_basic_info()
var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size)/4
let kerr: kern_return_t = withUnsafeMutablePointer(to: &info) {
$0.withMemoryRebound(to: integer_t.self, capacity: 1) {
task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count)
}
}
return kerr == KERN_SUCCESS ? Double(info.resident_size) / 1024.0 / 1024.0 : 0
}
private func topViewControllerDescriptions() -> String {
guard let root = UIApplication.shared.windows.first?.rootViewController else { return "" }
var desc = ""
var vc: UIViewController? = root
while vc != nil {
desc += "->\(type(of: vc!))"
vc = vc?.presentedViewController ?? (vc as? UINavigationController)?.visibleViewController
}
return desc
}
#endif
要点回顾:
- 整套代码用
#if BETA包裹,正式包直接裁剪,审核零风险; - 截屏用
UIGraphicsImageRenderer,不碰私有 API; - 上传用 Background Session+Wi-Fi 限制,省电省流量;
- 文件打包后立刻清理,不泄露用户数据;
- 所有文本日志脱敏,只留技术字段,满足《个保法》。
拓展思考
-
正式包怎么办?
iOS 16 开始苹果提供UIDevice.bugReportingAvailable与Show UIActivityViewController组合,但只能走 Apple 官方 Feedback,无法回传自己服务器。折中方案是:- 用 App Store Connect API 把 TestFlight 反馈拉到内部工单系统;
- 线上异常走 MetricKit+堆栈符号化,不再依赖截图。
-
录屏比截图信息量更大,能否自动上传?
ReplayKit 2 需要用户每次点“开始广播”,且 extension 内存限制 50 MB,无法后台偷偷跑;
如果做“点击悬浮球开始录屏”,属于用户主动操作,合规但路径长,灰度阶段可接受。 -
如何防止“测试截图里出现生产环境隐私数据”?
在 DEBUG 模式下给关键 UILabel 加accessibilityIdentifier = "sensitive",截图后遍历图层,对匹配标识的 view 打马赛克;
或者接入内部“ mock 数据工厂”,灰度包永远只显示假数据。 -
上传通道被公司安全部门要求走 VPN 内网?
用 NEHotspotConfiguration 给测试机自动下发企业 Wi-Fi 配置,上传域名解析到内网 DNS;
但注意 iOS 16 以后 NEHotspotConfiguration 必须用户二次确认,不能静默切换。 -
如果面试官追问“如何验证上传成功率和耗时”?
在 Background Session 的urlSession(_:task:didFinishDownloadingTo:)回调里把 statusCode、task.metrics.taskInterval 写入本地 sqlite,下次启动时回传,形成监控闭环;
同时用 MetricKit 上报后台唤醒次数,确保没有因上传导致电量异常。