2015-05-20 35 views
1

這個問題在Stack Overflow上被問過很多次,但仍然沒有確定的答案。這就是爲什麼我再次問。希望以一種明確的方式。Swift中SKScene中的社會框架

如何從SKScene的viewController調用社交函數?

這是touchesBegan功能在我SKScene:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { 
    for touch: AnyObject in touches { 
     let location = touch.locationInNode(self) 

     if self.nodeAtPoint(location) == self.twitterButton { 
      println("Twitter button") 
     } 

     if self.nodeAtPoint(location) == self.facebookButton { 
      println("Facebook button") 
     } 
    } 
} 

這是我GameViewController裏面的功能:

func postToFacebook() { 

    if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) { 
     var controller = SLComposeViewController(forServiceType: SLServiceTypeFacebook) 
     controller.setInitialText("Testing Posting to Facebook") 
     self.presentViewController(controller, animated:true, completion:nil) 

    } else { 
     println("no Facebook account found on device") 
    } 
} 
+0

還有一堆關於這個主題的教程! http://www.ioscreator.com/tutorials/facebook-tutorial-ios8-swift和http://sagarrkothari.com/sharing-via-facebook-in-ios-in-swift-using-slcomposeviewcontroller/和http:/ /www.thedarkdev.com/social-framework-ios8-using-swift-language.html – sangony

+0

@sangony是的,但他們不適合spritekit! –

+0

再次提問之前使用Google!用「SLComposeViewController sprite kit swift」進行簡單的搜索就會發現這個http://stackoverflow.com/questions/25595601/swift-spritekit-facebook-share-button – sangony

回答

3

您使用NSNotificationCenter從一個SKScene呈現viewController。請記住添加觀察者,然後發佈通知。當你不再需要NSNotification或者你的應用程序崩潰時,不要忘記取消NSNotification。

來自here的示例代碼。只需調整代碼的名稱從Twitter到Facebook,它應該工作。

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: { 
    //Optional completion statement 
    }) 

}