我很高兴找到skladek的答案,所以这是我的贡献:Swift和其他社交网络。
我发现Twitter需要3个正斜杠,而Facebook和Google+仅需要2个正斜杠,我没有做更多的调查……
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()