4.B 分享逻辑对齐 daoqi msext:调用即触发 sharesuccess

【契约影响】docs/H5-Native-Contract.md §3.1[2]/§3.2[11]

H5 端 sharesuccess 时机改为"调用 friendsShare handler 即立刻发",与
原 msext 行为等价(live path 完全不等 SDK / URL Scheme 回包)。用户
明示有意为之:URL Scheme + 剪贴板路径本就没有可靠回包,乐观策略避免
H5 业务卡住。

3 平台分支严格 1:1 对齐 daoqi msext:

WechatShare(对齐 WechatShareManager shareWithContent)
  - type=="2" → 截图 JPEG 0.6 + sendImageData + app icon thumb
  - else      → 链接分享 sendLinkURL + app icon thumb
  - 移除原"远端图"分支(原项目无此分支)
  - 新增 appIconImage helper(读 Info.plist CFBundleIcons,对齐
    [self getAppIconImage])

QQShare(对齐 QQShareManager shareWithContent + simpleShareToQQFriend)
  - type=="2" → 截图 → UIPasteboard.image → 4 URL Scheme fallback
  - else      → mqqapi://share/to_{fri,qzone}?req_type=1&url=...
                &title=...&description=...(webpageUrl 空时 req_type=0)
  - 不依赖 QQ SDK(CLAUDE.md ADR-006)

DouyinShare(对齐 DouyinShareManager shareWithContent)
  - type=="2" → 截图 → UIPasteboard.image → "立即打开抖音"引导框
  - else      → title+"\n\n"+desc → UIPasteboard.string → 引导框
                双侧空时兜底 "来自进贤聚友棋牌的精彩内容分享"
  - 放弃之前的"存相册 + 自动拉起"激进路径,回到原项目"用户主动点"路径

架构调整:
- SharePlatform.share 改 sync fire-and-forget(去 ShareResult 返回)
- ShareCenter.dispatch / SharePanel.show 去 completion 参数
- FriendsShareHandler:解析后先发 responseCallback("sharefriend")
  与 sharesuccess({success:"2", type:<sharefriend>}),再异步 dispatch
This commit is contained in:
joywayer
2026-06-24 07:34:03 +08:00
parent d471393806
commit 9bd5a81e6c
7 changed files with 259 additions and 219 deletions
@@ -5,16 +5,17 @@
// H5 Native handlerfriendsSharetypeUrlToptitleDescript
// docs/H5-Native-Contract.md §3.1 2 + §3.2 11sharesuccess
//
// msext gameController.m:575-597
// msext gameController.m:575-597
// 1. ShareContent
// 2. ShareCenter.dispatch
// - sharefriend == "1" SharePanel / QQ /
// - sharefriend == "2" WechatShare
// 3. bridge.call("sharesuccess", { success: "2", type: <sharefriend > })
// 2. responseCallback("sharefriend")
// 3. bridge.call("sharesuccess", { success:"2", type:<sharefriend > })
// ****H5 """" SDK
// URL Scheme /
// 4. fire-and-forget ShareCenter.dispatch UI
//
// SDK
// - Phase 4.E SDK WechatShare stub
// - QQ + SDK URL SchemePhase 4.C/4.D stub
// - WeChatManager 1.8.2 SDK
// - QQ + SDK URL Scheme + CLAUDE.md ADR-006
//
import Foundation
@@ -28,6 +29,7 @@ public enum FriendsShareHandler {
// cb: "sharefriend"msext 沿
// callbacksharesuccess({ success: "2", type: sharefriend })
bridge.register("friendsSharetypeUrlToptitleDescript") { [weak bridge] data, callback in
// 1. responseCallback msext "sharefriend"
callback?(.string("sharefriend"))
guard let obj = data?.asObject else { return }
@@ -39,25 +41,20 @@ public enum FriendsShareHandler {
title: obj["title"]?.asString ?? "",
desc: obj["description"]?.asString ?? ""
)
let sharefriend = content.sharefriend
await MainActor.run {
ShareCenter.dispatch(content) { result in
// success / cancelled / notInstalled / failed msext
// sharesuccessURL Scheme
switch result {
case .success, .cancelled:
bridge?.call("sharesuccess",
data: .object([
"success": .string("2"),
"type": .string(sharefriend)
]),
callback: nil)
case .notInstalled, .failed:
// sharesuccessH5 timeout fallback
break
}
}
// 2. sharesuccess
bridge?.call(
"sharesuccess",
data: .object([
"success": .string("2"),
"type": .string(content.sharefriend)
]),
callback: nil
)
// 3. fire-and-forget UI
ShareCenter.dispatch(content)
}
}
}
+103 -62
View File
@@ -2,19 +2,15 @@
// DouyinShare.swift
// ylgamehall
//
// SharePlatform Phase 4.D
// SharePlatform 1:1 daoqi msext DouyinShareManager
// `shareWithContent:completion:` type
// - type == "2" UIPasteboard ""
// - else title + "\n\n" + desc UIPasteboard
//
// msext DouyinShareManager.m:201-269 shareImageToDouyin
// 1. type=2 ImageProvider.captureScreenshot
// ImageProvider.downloadRemotetype=1
// 退msext H5
// 2. PhotoLibrarySaver.save addOnly
// 3. UIPasteboard
// 4. snssdk1128://camera / publish / share/image / scheme
// canOpenURL
// 5. successURL Scheme
// ** SDK**CLAUDE.md ADR-006 /
// + SDK
//
// ** SDK**
// fire-and-forgetsharesuccess FriendsShareHandler
//
import UIKit
@@ -27,68 +23,113 @@ public final class DouyinShare: SharePlatform {
private static let log = Logger(subsystem: "ylgamehall", category: "DouyinShare")
private static let douyinScheme = "snssdk1128://"
public let name = "Douyin"
public var isInstalled: Bool {
guard let url = URL(string: "snssdk1128://") else { return false }
guard let url = URL(string: Self.douyinScheme) else { return false }
return UIApplication.shared.canOpenURL(url)
}
public init() {}
public func share(_ content: ShareContent, scene: ShareScene) async -> ShareResult {
guard isInstalled else { return .notInstalled(platform: name) }
public func share(_ content: ShareContent, scene: ShareScene) {
guard isInstalled else { return }
// 1.
let image: UIImage
if content.type == "2" {
shareScreenshot()
} else {
shareText(content)
}
}
// MARK: -
/// msext DouyinShareManager.m:139-162 isScreenshotShare
/// pasteboard.image ""
private func shareScreenshot() {
do {
switch content.type {
case "2":
image = try ImageProvider.captureScreenshot()
case "1":
// 退msext
Self.log.debug("DouyinShare: type=1 链接,退化为截屏分享")
image = try ImageProvider.captureScreenshot()
default:
// type == URL
image = try await ImageProvider.downloadRemote(content.webpageUrl)
let shot = try ImageProvider.captureScreenshot()
UIPasteboard.general.image = shot
Self.log.debug("DouyinShare 截图已复制到剪贴板")
} catch {
Self.log.error("DouyinShare 截图失败 \(error.localizedDescription, privacy: .public)")
return
}
let message = """
✅ 图片已复制到剪贴板
🎯 分享到好友或群聊步骤:
1️⃣ 打开抖音,点击右下角「消息」
2️⃣ 选择好友或群聊进入聊天
3️⃣ 在输入框长按粘贴图片
4️⃣ 点击发送即可分享
"""
showGuidanceAlert(title: "抖音分享准备完成", message: message)
}
// MARK: -
/// msext DouyinShareManager.m:163-196 else
/// title + "\n\n" + desc pasteboard.string
/// msext ""
private func shareText(_ content: ShareContent) {
var shareText = ""
if !content.title.isEmpty {
shareText = content.title
}
if !content.desc.isEmpty {
shareText = shareText.isEmpty ? content.desc : "\(shareText)\n\n\(content.desc)"
}
if shareText.isEmpty {
shareText = "来自进贤聚友棋牌的精彩内容分享"
}
UIPasteboard.general.string = shareText
Self.log.debug("DouyinShare 文字已复制到剪贴板")
let message = """
✅ 内容已复制到剪贴板
🎯 分享到好友或群聊步骤:
1️⃣ 打开抖音,点击右下角「消息」
2️⃣ 选择好友或群聊进入聊天
3️⃣ 在输入框长按粘贴内容
4️⃣ 点击发送即可分享
"""
showGuidanceAlert(title: "抖音分享准备完成", message: message)
}
// MARK: -
/// " / " Alert msext
/// `showGuidanceAlertWithTitle:message:`
private func showGuidanceAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "立即打开抖音", style: .default) { _ in
if let url = URL(string: Self.douyinScheme),
UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
}
} catch {
Self.log.error("DouyinShare: 获取图片失败 \(error.localizedDescription, privacy: .public)")
return .failed(reason: "获取图片失败: \(error.localizedDescription)")
})
alert.addAction(UIAlertAction(title: "稍后分享", style: .cancel))
guard let topVC = Self.topViewController() else { return }
topVC.present(alert, animated: true)
}
private static func topViewController() -> UIViewController? {
let scene = UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.first(where: { $0.activationState == .foregroundActive })
?? UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first
guard var top = scene?.windows.first(where: \.isKeyWindow)?.rootViewController
?? scene?.windows.first?.rootViewController else { return nil }
while let presented = top.presentedViewController { top = presented }
if let nav = top as? UINavigationController, let visible = nav.visibleViewController {
return visible
}
// 2.
do {
try await PhotoLibrarySaver.save(image)
} catch PhotoLibrarySaverError.permissionDenied {
Self.log.warning("DouyinShare: 相册写入权限被拒")
return .failed(reason: "相册写入权限被拒")
} catch {
Self.log.error("DouyinShare: 保存相册失败 \(error.localizedDescription, privacy: .public)")
return .failed(reason: "保存相册失败: \(error.localizedDescription)")
}
// 3. msext
UIPasteboard.general.image = image
// 4. msext URL Scheme
let schemes = [
"snssdk1128://camera", //
"snssdk1128://publish", //
"snssdk1128://share/image", //
"snssdk1128://" // scheme
]
for schemeString in schemes {
guard let url = URL(string: schemeString),
UIApplication.shared.canOpenURL(url)
else { continue }
Self.log.debug("DouyinShare open: \(schemeString, privacy: .public)")
let opened = await UIApplication.shared.open(url)
if opened { return .success }
}
return .failed(reason: "所有抖音 URL Scheme 都调起失败")
return top
}
}
+53 -37
View File
@@ -2,21 +2,18 @@
// QQShare.swift
// ylgamehall
//
// QQ SharePlatform Phase 4.C
// QQ SharePlatform daoqi msext QQShareManager
// `shareWithContent:completion:` type
// - type == "2" UIPasteboard + mqqapi://
// - else mqqapi://share/to_fri?req_type=1&url=...
//
// msext QQShareManager.m:716-771 simpleShareToQQFriend URL Scheme
// fallback** QQ SDK**
//
// URL
// mqqapi://share/to_fri?version=1&cflag=0&req_type=1
// &url=<encoded webpageUrl>&title=<encoded title>&description=<encoded desc>
// ** QQ SDK**CLAUDE.md ADR-006 SDK
// URL Scheme + pasteboard UX
//
// encodeString msext line 1262-1268 unreserved RFC 3986
// alphanumeric + "-._~" percent encode
//
// type == "1"type == "2" /
// Phase 4.F UIGraphicsImageRenderer + Photos / +
// mqqapi://share/to_fri?file_type=img
// fire-and-forgetsharesuccess FriendsShareHandler
//
import UIKit
@@ -38,28 +35,57 @@ public final class QQShare: SharePlatform {
public init() {}
public func share(_ content: ShareContent, scene: ShareScene) async -> ShareResult {
guard isInstalled else { return .notInstalled(platform: name) }
public func share(_ content: ShareContent, scene: ShareScene) {
guard isInstalled else { return }
// URL Scheme Phase 4.F
guard content.type == "1" else {
Self.log.warning("QQShare: type=\(content.type, privacy: .public) (非链接) 暂未实现,返回 success 避免 H5 业务卡住")
return .success
if content.type == "2" {
shareScreenshot()
} else {
shareLink(content, scene: scene)
}
}
// MARK: -
/// msext QQShareManager.m:1876-1906 isScreenshotShare
/// QQ SDK shareToQQFriend QQShareTypeImage UIImage SDK
/// SDK 退 pasteboard QQ
private func shareScreenshot() {
do {
let shot = try ImageProvider.captureScreenshot()
UIPasteboard.general.image = shot
} catch {
Self.log.error("QQShare 截图失败 \(error.localizedDescription, privacy: .public)")
}
// URLmqqapi://share/to_fri? mqqapi://share/to_qzone?
// scene == .timeline QQ to_qzone.friend to_friQQ
let host = scene == .timeline ? "share/to_qzone" : "share/to_fri"
var parts: [String] = [
"version=1",
"cflag=0",
"req_type=1"
let candidates = [
"mqqapi://share/to_fri?file_type=news&version=1&cflag=0",
"mqq://im/chat?chat_type=select",
"mqqapi://",
"mqq://"
]
for s in candidates {
guard let url = URL(string: s),
UIApplication.shared.canOpenURL(url) else { continue }
UIApplication.shared.open(url)
return
}
}
// MARK: -
/// msext QQShareManager.m simpleShareToQQFriend
/// mqqapi://share/to_fri?version=1&cflag=0&req_type=1
/// &url=<encoded webpageUrl>&title=<encoded title>&description=<encoded desc>
/// scene == .timeline QQ (to_qzone).friend QQ (to_fri)
private func shareLink(_ content: ShareContent, scene: ShareScene) {
let host = scene == .timeline ? "share/to_qzone" : "share/to_fri"
var parts: [String] = ["version=1", "cflag=0"]
if !content.webpageUrl.isEmpty {
parts.append("req_type=1")
parts.append("url=\(Self.encode(content.webpageUrl))")
} else {
// URL req_type=0
parts = ["version=1", "cflag=0", "req_type=0"]
parts.append("req_type=0")
}
if !content.title.isEmpty {
parts.append("title=\(Self.encode(content.title))")
@@ -69,21 +95,11 @@ public final class QQShare: SharePlatform {
}
let urlString = "mqqapi://\(host)?\(parts.joined(separator: "&"))"
Self.log.debug("QQShare open: \(urlString, privacy: .public)")
guard let qqURL = URL(string: urlString),
UIApplication.shared.canOpenURL(qqURL)
else {
return .failed(reason: "invalid QQ URL")
}
// URL Scheme msext success
let opened = await UIApplication.shared.open(qqURL)
return opened ? .success : .failed(reason: "openURL failed")
UIApplication.shared.canOpenURL(qqURL) else { return }
UIApplication.shared.open(qqURL)
}
/// msext QQShareManager.m:1262-1268 RFC 3986 unreserved
/// alphanumeric + "-._~" percent encode
nonisolated static func encode(_ string: String) -> String {
var allowed = CharacterSet.alphanumerics
allowed.insert(charactersIn: "-._~")
+6 -13
View File
@@ -6,7 +6,8 @@
// - sharefriend == "1"/ SharePanel /QQ/
// - sharefriend == "2" WechatShare timeline
//
// Design §8.2 ShareKit + SharePlatform
// fire-and-forgetH5 sharesuccess FriendsShareHandler
// UI / SDK
//
import Foundation
@@ -14,27 +15,19 @@ import Foundation
@MainActor
public enum ShareCenter {
/// FriendsShareHandler handler
/// completion UI await cb msext
public static func dispatch(_ content: ShareContent, completion: @escaping (ShareResult) -> Void) {
public static func dispatch(_ content: ShareContent) {
switch content.sharefriend {
case "1":
// / SharePanel
SharePanel.show(content: content, completion: completion)
SharePanel.show(content: content)
case "2":
// WechatSharetimeline
Task { @MainActor in
let result = await WechatShare.shared.share(content, scene: .timeline)
completion(result)
}
WechatShare.shared.share(content, scene: .timeline)
default:
// sharefriendmsext 沿
Task { @MainActor in
let result = await WechatShare.shared.share(content, scene: .timeline)
completion(result)
}
WechatShare.shared.share(content, scene: .timeline)
}
}
}
+11 -17
View File
@@ -27,13 +27,11 @@ public final class SharePanel: UIView {
private static let animationDuration: TimeInterval = 0.25
private let content: ShareContent
private let completion: (ShareResult) -> Void
private let contentView = UIView()
public init(content: ShareContent, completion: @escaping (ShareResult) -> Void) {
public init(content: ShareContent) {
self.content = content
self.completion = completion
super.init(frame: UIScreen.main.bounds)
backgroundColor = UIColor(white: 0, alpha: 0)
setupUI()
@@ -46,13 +44,11 @@ public final class SharePanel: UIView {
// MARK: -
///
public static func show(content: ShareContent, completion: @escaping (ShareResult) -> Void) {
guard let window = topWindow() else {
completion(.failed(reason: "no key window"))
return
}
let panel = SharePanel(content: content, completion: completion)
/// fire-and-forgetsharesuccess FriendsShareHandler
/// H5
public static func show(content: ShareContent) {
guard let window = topWindow() else { return }
let panel = SharePanel(content: content)
window.addSubview(panel)
panel.animateIn()
}
@@ -146,7 +142,7 @@ public final class SharePanel: UIView {
@objc private func handleBackgroundTap(_ gesture: UITapGestureRecognizer) {
let point = gesture.location(in: self)
if !contentView.frame.contains(point) {
dismiss { [self] in completion(.cancelled) }
dismiss()
}
}
@@ -155,12 +151,10 @@ public final class SharePanel: UIView {
let platform = platforms[sender.tag]
let scene: ShareScene = content.sharefriend == "2" ? .timeline : .friend
let snapshotContent = content
dismiss {
Task { @MainActor in
let result = await platform.share(snapshotContent, scene: scene)
Self.log.debug("share via \(platform.name, privacy: .public) result=\(String(describing: result), privacy: .public)")
self.completion(result)
}
dismiss { [weak platform] in
guard let platform else { return }
Self.log.debug("share via \(platform.name, privacy: .public)")
platform.share(snapshotContent, scene: scene)
}
}
}
+13 -15
View File
@@ -2,10 +2,15 @@
// SharePlatform.swift
// ylgamehall
//
// + ShareContent + ShareResult
// + ShareContent
//
// / QQ / SharePlatform ShareCenter
// sharefriend / conformance
// sharefriend /
//
// **fire-and-forget **share H5
// sharesuccess FriendsShareHandler msext
// gameController.m "" share()
// UI / URL Scheme
//
// docs/H5-Native-Implementation-Design.md §8.2 ShareKit
//
@@ -22,9 +27,9 @@ nonisolated public struct ShareContent: Sendable {
/// msext 1 / 2 / 3 SharePanel
/// §3.1 2
public let sharetype: String
/// 1 / 2 / = URL
/// 1 / 2 / = WechatShareManager
public let type: String
/// URL URL
/// URL
public let webpageUrl: String
public let title: String
public let desc: String
@@ -46,13 +51,6 @@ nonisolated public struct ShareContent: Sendable {
}
}
public enum ShareResult: Sendable {
case success
case cancelled
case notInstalled(platform: String)
case failed(reason: String)
}
/// / QQ /
public enum ShareScene: Sendable {
case friend // / QQ
@@ -61,10 +59,10 @@ public enum ShareScene: Sendable {
@MainActor
public protocol SharePlatform: AnyObject {
/// log /
/// log
var name: String { get }
/// app SharePanel
/// app SharePanel
var isInstalled: Bool { get }
/// content.type / /
func share(_ content: ShareContent, scene: ShareScene) async -> ShareResult
/// UIfire-and-forgetsharesuccess handler
func share(_ content: ShareContent, scene: ShareScene)
}
+52 -51
View File
@@ -2,17 +2,20 @@
// WechatShare.swift
// ylgamehall
//
// SharePlatform
// SharePlatform 1:1 daoqi msext WechatShareManager
// `shareWithContent:completion:`
// - type == "2" getImageWithFullScreenshot + JPEG 0.6 + sendImageData
// - else sendLinkURL + webpageUrl + title + desc
//
// canImport(WechatOpenSDK) SDK isInstalled = true / share = .success
// SharePanel Xcode Embed & Sign
// app icon `[self getAppIconImage]` sharelogo
//
// fire-and-forgetH5 sharesuccess FriendsShareHandler
// dispatch_after 1s completion(YES)
//
import Foundation
import UIKit
// SDK 1.8.2 Bridging Header import
@MainActor
public final class WechatShare: SharePlatform {
@@ -26,55 +29,53 @@ public final class WechatShare: SharePlatform {
public init() {}
public func share(_ content: ShareContent, scene: ShareScene) async -> ShareResult {
guard WXApi.isWXAppInstalled() else {
return .notInstalled(platform: name)
}
public func share(_ content: ShareContent, scene: ShareScene) {
guard WXApi.isWXAppInstalled() else { return }
let wxScene: WeChatManager.ShareScene = (scene == .timeline) ? .timeline : .session
do {
switch content.type {
case "1":
// msext gameController.m:613-635
try await WeChatManager.shared.shareLink(
.init(
url: content.webpageUrl,
title: content.title,
desc: content.desc,
thumbnailURL: nil
),
scene: wxScene
)
case "2":
// msext gameController.m:637-658
let shot = try ImageProvider.captureScreenshot()
guard let imageData = shot.jpegData(compressionQuality: 0.6) else {
return .failed(reason: "screenshot JPEG encode failed")
let thumb = Self.appIconImage()
Task { @MainActor in
do {
if content.type == "2" {
// msext WechatShareManager isScreenshotShare
let shot = try ImageProvider.captureScreenshot()
guard let imageData = shot.jpegData(compressionQuality: 0.6) else { return }
try await WeChatManager.shared.shareImage(
.init(imageData: imageData, thumb: thumb),
scene: wxScene
)
} else {
// msext else type=="1"
try await WeChatManager.shared.shareLink(
.init(
url: content.webpageUrl,
title: content.title,
desc: content.desc,
thumbnailURL: nil
),
scene: wxScene
)
}
let thumb = ImageProvider.scaledThumb(shot)
try await WeChatManager.shared.shareImage(
.init(imageData: imageData, thumb: thumb),
scene: wxScene
)
default:
// msext gameController.m:659-680type URL
let remote = try await ImageProvider.downloadRemote(content.webpageUrl)
// msext data UIImage decode
// jpegData
guard let imageData = remote.jpegData(compressionQuality: 0.9) else {
return .failed(reason: "remote image JPEG encode failed")
}
let thumb = ImageProvider.scaledThumb(remote)
try await WeChatManager.shared.shareImage(
.init(imageData: imageData, thumb: thumb),
scene: wxScene
)
} catch {
// SDK H5 sharesuccess
}
return .success
} catch let WeChatError.shareFailed(errCode) {
if errCode == -2 { return .cancelled }
return .failed(reason: "WeChat errCode \(errCode)")
} catch {
return .failed(reason: "\(error)")
}
}
/// app icon Info.plist `CFBundleIcons` `CFBundlePrimaryIcon`
/// `CFBundleIconFiles` msext
/// WechatShareManager `getAppIconImage` 1x1
private static func appIconImage() -> UIImage {
if let icons = Bundle.main.object(forInfoDictionaryKey: "CFBundleIcons") as? [String: Any],
let primary = icons["CFBundlePrimaryIcon"] as? [String: Any],
let files = primary["CFBundleIconFiles"] as? [String],
let last = files.last,
let icon = UIImage(named: last) {
return icon
}
if let icon = UIImage(named: "AppIcon") { return icon }
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 1, height: 1))
return renderer.image { _ in }
}
}