Swift2 SpriteKit推特分享错误

时间:2016-06-15 04:13:54

标签: ios xcode swift swift2

我正在尝试通过twitter实现共享并且该功能看起来不错但是当点击该按钮时,我的GameScene中出现错误。

在这条直线上:     let skView = self.view as! SKView 错误:线程1 SIGARBT

我整天都被困在这里。任何帮助都会很棒

var vc = GameViewController()
vc.showTweetSheet() // button click causes error ^ ^ ^ 

// GameView

class GameViewController: UIViewController {

func showTweetSheet() {
    let tweetSheet = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
    tweetSheet.completionHandler = {
        result in
        switch result {
        case SLComposeViewControllerResult.Cancelled:
            //Add code to deal with it being cancelled
            break

        case SLComposeViewControllerResult.Done:
            //Add code here to deal with it being completed
            //Remember that dimissing the view is done for you, and sending the tweet to social media is automatic too. You could use this to give in game rewards?
            break
        }
    }

    tweetSheet.setInitialText("Test Twitter") //The default text in the tweet
    tweetSheet.addImage(UIImage(named: "TestImage.png")) //Add an image if you like?
    tweetSheet.addURL(NSURL(string: "http://twitter.com")) //A url which takes you into safari if tapped on

    self.presentViewController(tweetSheet, animated: false, completion: {
        NSNotificationCenter.defaultCenter().postNotificationName("Whatever", object: nil)
    })
}

 override func viewDidLoad() {
    super.viewDidLoad()

    if let scene = GameScene(fileNamed:"GameScene") {
        // Configure the view.
        let skView = self.view as! SKView //ERROR HAPPENS HEREE (ONLY ON CLK
        skView.showsFPS = false 
        skView.showsNodeCount = false

        /* Sprite Kit applies additional optimizations to improve rendering performance */
        skView.ignoresSiblingOrder = true

        /* Set the scale mode to scale to fit the window */
        scene.scaleMode = .AspectFill
        scene.size = self.view.bounds.size

        skView.presentScene(scene)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "ThisIsTheMethodName", name: "Whatever", object: nil)
    }
}

1 个答案:

答案 0 :(得分:0)

你的方法不起作用,你正在创建一个新的GameViewController实例,而不是访问当前的GameViewController

 var vc = GameViewController() // This creates new instance of GameViewController

访问当前gameViewController的最佳方法通常是使用委托或NSNotificationCenter,而不是获取对它的引用。

您也可以将您的shareSheet函数放入GameScene并在rootViewController上显示。

  self.view?.window?.rootViewController?.presentViewController(tweetSheet...

作为替代方案,我建议您制作可重复使用的助手,以便在未来的游戏中重复使用此代码会更容易。

我在Swift 2中使用协议扩展来实现这一目标。创建一个新的swift文件,调用类似SocialHelper的东西并添加此代码(只需复制2个方法并将其更改为twitter,代码是相同的)

  import SpriteKit
  import Social

 /// URLs
 private struct URL {
          static let iTunesApp = NSURL(string: "Your iTunes app link")
          static let facebookApp = NSURL(string: "Your Facebook app link")
          static let facebookWeb = NSURL(string: "Your Facebook web link")
  }

   /// Text strings
  private struct TextString {
       static let shareSheetText = "Can you beat my score"
       static let error = "Error"
       static let enableSocial = "Please sign in to your account first"
       static let settings = "Settings"
      static let ok = "OK"
  }

  /// Social
  protocol Social {}
  extension Social where Self: SKScene {

  /// Open facebook
 func openFacebook() {
      guard let facebookApp = URL.facebookApp else { return }
      guard let facebookWeb = URL.facebookWeb else { return }

      if UIApplication.sharedApplication().canOpenURL(facebookApp){     
          UIApplication.sharedApplication().openURL(facebookApp)
     } else {
        UIApplication.sharedApplication().openURL(facebookWeb)
   }
}

  /// Share to facebook
  func shareToFacebook() {

      guard SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) else {
             showAlert()
             return
       }

     let facebookSheet = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
     facebookSheet.completionHandler = { result in

           switch result {

           case .Cancelled:
               print("Facebook message cancelled")
              break

          case .Done:
              print("Facebook message complete")
              break
          }
      }

      let text = TextString.shareSheetText //
      facebookSheet.setInitialText(text) // share sheet text for Facebook will not work anymore if app is installed
    facebookSheet.addImage(Your UIImage)
    //facebookSheet.addURL(URL.iTunesApp) // seems to mess up image, Facebook only

        self.view?.window?.rootViewController?.presentViewController(facebookSheet, animated: true, completion: nil)
     }

   /// Show alert
  private func showAlert() {
        let alertController = UIAlertController(title: TextString.error, message: TextString.enableSocial, preferredStyle: .Alert)

        let okAction = UIAlertAction(title: TextString.ok, style: .Cancel) { _ in }
          alertController.addAction(okAction)

       let settingsAction = UIAlertAction(title: TextString.settings, style: .Default) { _ in

          if let url = NSURL(string: UIApplicationOpenSettingsURLString) {
             UIApplication.sharedApplication().openURL(url)
         }
     }
     alertController.addAction(settingsAction)

   self.view?.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
      }
  }

现在,在场景中,你想要显示shareSheet,你只需遵守proctocol

  class YourScene: SKScene, Social {....

并将该方法称为场景本身的一部分。

 openFacebook()    // opens app or safari
 shareToFacebook()

希望这有帮助