我正试图在我的SocialMediaSharingDelegate中创建一种标准化的社交媒体分享方法。就像我在facebookShare方法中所做的那样,指定一个单独的社交媒体服务非常好用。因此,为了扩展这一点,我创建了一个具有可能的服务类型的枚举,shareOn方法接受任何有效的服务名称来执行共享。
这看起来很简单。但是,当我运行代码并单击调用shareOn方法的按钮时,我得到一个运行时错误。在让serviceViewController...行上出现错误"fatal error: unexpectedly nil while an Optional value“。就在守卫口供之后。
如果我在该行将socialMediaService.associatedService()替换为SLServiceTypeFacebook,也可以很好地工作,这很奇怪,因为在guard语句中使用socialMediaService.associatedService()没有问题。
目前,我只能为每个服务创建单独的函数,但就代码重用而言,这并不理想。
import Foundation
import UIKit
import Social
enum SocialMediaEnum : String {
case Twitter = "SLServiceTypeTwitter"
case Facebook = "SLServiceTypeFacebook"
// This internal enum function returns the SLServiceType associated with the current enum value
func associatedService() -> String {
var serviceName: String
switch self {
case .Twitter:
serviceName = "SLServiceTypeTwitter"
case .Facebook:
serviceName = "SLServiceTypeFacebook"
}
return serviceName
}
}
class socialMediaSharing : SocialMediaSharingDelegate {
func shareOn(let socialMediaService: SocialMediaEnum, sender: subclassedUIButton?, currentViewController: UIViewController) {
guard SLComposeViewController.isAvailableForServiceType(socialMediaService.associatedService()) else {
let alert = UIAlertController(title: "Accounts", message: "Please login to a Twitter account to tweet.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
currentViewController.presentViewController(alert, animated: true, completion: nil)
return
}
let serviceViewController :SLComposeViewController = SLComposeViewController(forServiceType: socialMediaService.associatedService())
if let imageUrl = sender?.urlString {
if let url:NSURL = NSURL(string: imageUrl as String) {
serviceViewController.addURL(url)
}
}
currentViewController.presentViewController(serviceViewController, animated: true, completion: nil)
}
func facebookShare(sender: subclassedUIButton?, currentViewController: UIViewController) {
guard SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) else {
let alert = UIAlertController(title: "Accounts", message: "Please login to a Facebook account to share.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
currentViewController.presentViewController(alert, animated: true, completion: nil)
return
}
let shareToFacebook :SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
if let imageUrl = sender?.urlString {
if let url:NSURL = NSURL(string: imageUrl as String) {
shareToFacebook.addURL(url)
}
}
currentViewController.presentViewController(shareToFacebook, animated: true, completion: nil)
}
}发布于 2015-10-10 22:34:59
SLServiceTypeTwitter和SLServiceTypeFacebook是关键字,因此在switch语句中不应该有引号。它们实际持有的值是“com.apple.social.(服务名称)”。
https://stackoverflow.com/questions/33022202
复制相似问题