You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS图片上传:如何将Firebase进度计数单位转换为百分比

Convert Raw Progress Unit Counts to Percentage (0%-100%) for iOS Image Uploads

Hey there! Great job getting basic progress tracking up and running—turning those raw unit numbers like 32, 485, etc., into a clean percentage is super simple once you leverage the full capabilities of the Progress object.

The Key: Use totalUnitCount Alongside completedUnitCount

The Progress instance you're accessing from the snapshot has two critical properties for calculating percentage:

  • completedUnitCount: The number of units you've already uploaded (the numbers you're seeing now)
  • totalUnitCount: The total number of units needed to finish the upload

By dividing these two values and multiplying by 100, you'll get your 0-100% progress. Here's how to update your code:

uploading.observe(.progress) { [weak self] snapshot in
    // Guard against nil progress and avoid division by zero
    guard let progress = snapshot.progress, progress.totalUnitCount > 0 else {
        self?.navigationItem.title = "0%"
        return
    }
    
    // Calculate percentage as a Double
    let progressPercentage = (Double(progress.completedUnitCount) / Double(progress.totalUnitCount)) * 100
    
    // Round to a whole number for cleaner display (optional)
    let roundedPercentage = Int(progressPercentage.rounded())
    
    // Update the navigation bar title with the percentage
    self?.navigationItem.title = "\(roundedPercentage)%"
}

Important Notes:

  • Avoid Retain Cycles: I added [weak self] to the closure to prevent a potential memory leak—this is a best practice when referencing self in async closures.
  • Handle Edge Cases: The guard clause checks that totalUnitCount is greater than 0 to avoid division by zero errors, which can happen if the total hasn't been calculated yet when the first progress update fires.
  • Precision Control: If you want more precise progress (like 75.2% instead of 75%), skip the rounding step and format the Double directly (e.g., String(format: "%.1f%%", progressPercentage)).

That's it! This will give you a clean, user-friendly percentage that updates as your image uploads.

内容的提问来源于stack exchange,提问作者user8922356

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:44:30