SwiftUI中Twitter URL跳转失效及发推链接问题咨询
问题1:SwiftUI中Link跳转Twitter主页失败的解决办法
错误原因
你使用的twitter://user?screen_name=nikolomoec URL Scheme已不被Twitter(现X)支持,导致应用无法识别该URL,触发NSOSStatusErrorDomain Code=-10814错误。
修复方案
替换为有效URL Scheme
Twitter官方当前支持的用户主页跳转格式为:URL(string: "twitter://profile?screen_name=nikolomoec")!若设备上安装的是X应用,也可使用
x://profile?screen_name=nikolomoec替代。优化URL安全处理
避免强制解包URL,添加可选绑定防止崩溃:if let twitterURL = URL(string: "twitter://profile?screen_name=nikolomoec") { Link(destination: twitterURL) { ZStack { RoundedRectangle(cornerRadius: 10) .frame(height: geo.size.height / 5) .foregroundStyle(.bar) .translucentStroke(10) HStack { Text("Twitter DMs") .font(.title3.bold()) Spacer() Image("Twitter") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 30, height: 30) .contentShape(Rectangle()) } .padding(.horizontal, 25) } } }
问题2:跳转至Twitter发推界面并自动填充指定链接
使用Twitter的post Scheme参数即可实现,具体代码示例如下:
// 替换为你需要填充的链接和文本内容 let tweetContent = "分享链接:https://your-link-here.com" if let encodedContent = tweetContent.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let tweetURL = URL(string: "twitter://post?message=\(encodedContent)") { Link(destination: tweetURL) { Text("发布推文") } }
关键说明
- 必须对推文内容做
addingPercentEncoding编码,确保空格、链接等特殊字符能被正确识别。 - 若使用X应用,可将Scheme替换为
x://post?message=\(encodedContent)。
内容的提问来源于stack exchange,提问作者Nikita Kolomoec
相关产品推荐
相关产品推荐

