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

使用UIActivityViewController同时分享网络图片与视频遇问题求解决方案

解决UIActivityViewController同时分享图片与视频的问题

原代码存在的问题

  • 变量名不匹配:初始化UIActivityViewController时用了未定义的items,实际应该用objectsToShare
  • 同步加载视频阻塞主线程:NSData(contentsOf:)是同步方法,会卡住UI,严重影响体验
  • 图片类型可能不兼容:如果imageData是Data类型,需要转为UIImage才能被分享控制器正确识别
  • iPad适配使用旧API:CGRectMake、CGRectGetMidX/Y属于Objective-C时代的旧API,Swift中应使用原生属性替代

可行解决方案代码

// 假设imageData是Data类型,先转为UIImage
guard let image = UIImage(data: imageData),
      let videoURL = photo.videoURL as? URL else {
    return
}

// 异步下载视频,避免阻塞主线程
let task = URLSession.shared.dataTask(with: videoURL) { data, response, error in
    guard let data = data, error == nil else {
        print("视频下载失败: \(error?.localizedDescription ?? "未知错误")")
        return
    }
    
    // 保存视频到本地文档目录
    let fileManager = FileManager.default
    guard let docDir = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
        return
    }
    let videoFilePath = docDir.appendingPathComponent("tmpVideo.mov")
    
    do {
        try data.write(to: videoFilePath)
    } catch {
        print("视频保存失败: \(error.localizedDescription)")
        return
    }
    
    // 回到主线程处理UI
    DispatchQueue.main.async {
        // 准备分享内容:UIImage + 本地视频URL
        let objectsToShare: [Any] = [image, videoFilePath]
        
        let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
        
        // iPad适配:设置popover的展示位置
        if UIDevice.current.userInterfaceIdiom == .pad {
            activityVC.popoverPresentationController?.sourceView = viewController.view
            // 设置popover从视图中心弹出
            let center = viewController.view.center
            activityVC.popoverPresentationController?.sourceRect = CGRect(x: center.x, y: center.y, width: 0, height: 0)
            activityVC.popoverPresentationController?.permittedArrowDirections = []
        }
        
        viewController.present(activityVC, animated: true)
    }
}
task.resume()

额外注意事项

  • 部分分享渠道(比如微信、微博)可能不支持同时分享图片和视频,需要提前测试各平台的兼容性
  • 本地视频文件在分享完成后可以考虑删除,避免占用存储空间:try? fileManager.removeItem(at: videoFilePath)
  • 确保photo.videoURL是有效的可访问URL,避免下载失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 20:05:31