我很高兴找到 skladek 的答案,所以这是我的贡献:Swift + 其他社交网络。
我发现 twitter 需要 3 个正斜杠,而 Facebook 和 Google+ 只需要 2 个,我没有调查更多……</p>
// Go to https://graph.facebook.com/PageName to get your page id
func openFacebookPage() {
let facebookURL = NSURL(string: "fb://profile?id=PageName")!
if UIApplication.sharedApplication().canOpenURL(facebookURL) {
UIApplication.sharedApplication().openURL(facebookURL)
} else {
UIApplication.sharedApplication().openURL(NSURL(string: "https://www.facebook.com/PageName")!)
}
}
func openTwitterProfile() {
let twitterURL = NSURL(string: "twitter:///user?screen_name=USERNAME")!
if UIApplication.sharedApplication().canOpenURL(twitterURL) {
UIApplication.sharedApplication().openURL(twitterURL)
} else {
UIApplication.sharedApplication().openURL(NSURL(string: "https://twitter.com/USERNAME")!)
}
}
func openGooglePlusPage() {
let googlePlusURL = NSURL(string: "gplus://plus.google.com/u/0/PageId")!
if UIApplication.sharedApplication().canOpenURL(googlePlusURL) {
UIApplication.sharedApplication().openURL(googlePlusURL)
} else {
UIApplication.sharedApplication().openURL(NSURL(string: "https://plus.google.com/PageId")!)
}
}
重构的尝试:
struct SocialNetworkUrl {
let scheme: String
let page: String
func openPage() {
let schemeUrl = NSURL(string: scheme)!
if UIApplication.sharedApplication().canOpenURL(schemeUrl) {
UIApplication.sharedApplication().openURL(schemeUrl)
} else {
UIApplication.sharedApplication().openURL(NSURL(string: page)!)
}
}
}
enum SocialNetwork {
case Facebook, GooglePlus, Twitter, Instagram
func url() -> SocialNetworkUrl {
switch self {
case .Facebook: return SocialNetworkUrl(scheme: "fb://profile/PageId", page: "https://www.facebook.com/PageName")
case .Twitter: return SocialNetworkUrl(scheme: "twitter:///user?screen_name=USERNAME", page: "https://twitter.com/USERNAME")
case .GooglePlus: return SocialNetworkUrl(scheme: "gplus://plus.google.com/u/0/PageId", page: "https://plus.google.com/PageId")
case .Instagram: return SocialNetworkUrl(scheme: "instagram://user?username=USERNAME", page:"https://www.instagram.com/USERNAME")
}
}
func openPage() {
self.url().openPage()
}
}
现在您可以致电:
SocialNetwork.Twitter.openPage()