Swift Spritekit Facebook Share Button

swift spritekit Facebook share button

This is some code I did for twitter a while ago which still works in swift. I show you how to convert it to Facebook below. Put this your viewController:

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
})
}

To convert it to Facebook, simply swap SLServiceTypeTwitter to SLServiceTypeFacebook and rename the variables for readability. If you want to call this method from the SKScene, you have to somehow alert the viewController that you want it to call a method.

My preferred way is to use NSNotificationCenter so that I post an alert from the scene and it is received by the viewController so that it fires a method. This is also incredibly easy to setup. In the scene, you need to put this line of code wherever you want to call the Facebook popup:

NSNotificationCenter.defaultCenter().postNotificationName("WhateverYouWantToCallTheNotification", object: nil)

This sends out a notification with a name. Now, in the viewController you need to subscribe to this alert by putting the following code in either viewDidLoad, viewDidAppear or something similar.

NSNotificationCenter.defaultCenter().addObserver(self, selector: "ThisIsTheMethodName", name: "WhateverYouCalledTheAlertInTheOtherLineOfCode", object: nil)

Now the scene will communicate with the viewController and you will be able to show the Facebook sheet. Remember to replace my strings with ones relative to your project. Hope this helps - sorry it was such a long answer!

How can I create a 'share to Facebook button' in a SpriteKit game using swift?

Update: If you are targeting iOS 9 or above there are some small changes to make this work. You will need to add the correct URL schemes to your info.plist otherwise the check to see if the app is installed will not work.

NOTE: Its is a better idea to now use UIActivityController for sharing. This allows you to only use 1 button and you can share to all sorts of services.

http://useyourloaf.com/blog/querying-url-schemes-with-canopenurl/

To present a viewController in a SKScene you need to use the rootViewController

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

I use a little helper for this using swift 2 protocol extensions, so you can use it anywhere you like in your app. The Facebook part looks like this, twitter is basically the same.

import SpriteKit
import Social

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

/// Text strings
private struct TextString {
static let shareSheetText = "Your share sheet text"
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 = URLString.facebookApp else { return }
guard let facebookWeb = URLString.facebookWeb else { return }

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

/// Share to facebook
func shareToFacebook() {

guard SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook) else {
showAlert()
return
}

guard let facebookSheet = SLComposeViewController(forServiceType: SLServiceTypeFacebook) else { return }
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)
facebookSheet.setInitialText(String.localizedStringWithFormat(text, "add your score property")) // same as line above but with a score property
facebookSheet.addImage(Your UIImage)
facebookSheet.add(URLString.iTunesApp)

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

// MARK: - Private Methods

/// 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 = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.openURL(url)
}
}
alertController.addAction(settingsAction)

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

To use the helper you simply go to the SKScene you need to call the methods and implement the protocol

 class YourScene: SKScene, Social {....

Now when the Facebook node/button is pressed you can call the methods as if they are part of the scene itself.

openFacebook()    // opens app or safari
shareToFacebook() // opens share sheet textField

all thanks to swift 2 and protocol extensions. The cool bit about this is say you want to use this helper in a regular UIKit app, than all you have to do is import UIKit instead of spriteKit

 import UIKit

and change the protocol extension to this

 extension Social where Self: UIViewController {....

Its quite nice and very flexible I think

Hope this helps.

How to fix the share button on SpriteKit Swift when Players plays the game again Share Button shows up on the game scene?

The first rule when making a SpriteKit game is to try to not use UIKit.
All of your UI should be created directly in the SKScenes using SpriteKit APIs (SKLabelNodes, SKSpriteNodes, SKNodes etc).
There are exceptions to this, like maybe using UICollectionViews for massive level select menus, but basic UI should never be done using UIKit.

So you should be making your buttons using SKSpriteNodes and add them directly to the SKScene you want.

There are plenty of tutorials to google on how to do this, a simple one is this

https://nathandemick.com/2014/09/buttons-sprite-kit-using-swift/

For a more complete one check out apples sample game "DemoBots" or have a look at these cool projects on gitHub.

https://github.com/nguyenpham/sgbutton

https://github.com/jozemite/JKButtonNode

In SpriteKit games you only tend to have 1 view Controller (GameViewController) which will present all your SKScenes (GameScene, MenuScene etc). If you use UIKit elements they get added to the GameViewController, and therefore they will be shown in all scenes (like your share button).

self.view?.addSubview(shareButton) // self.view is your GameViewController

If you have a game with more than 1 SKScene and quite a few buttons this will be madness to manage.

On the other hand if you use SpriteKit APIs, and because every SKScene starts in a clean state when you enter it, you dont have to worry about any of this.

If you insist on using UIKit than you will have to either remove or hide the share button before you transition to game scene and unhide it or add it again when you want to.

 shareButton.isHidden = true

or

 shareButton.removeFromSuperview()

Finally as good practice your properties should start with small letters not capital letters

shareButton = ...

Hope this helps

Add a share button - Swift

This code will bring up an activity view and will let you share whatever you want with it.

if var top = scene?.view?.window?.rootViewController {
while let presentedViewController = top.presentedViewController {
top = presentedViewController
}
let activityVC = UIActivityViewController(activityItems: ["This is an array of items that will be shared. Including Images, Numbers, and text (like this)"], applicationActivities: nil)
activityVC.popoverPresentationController?.sourceView = view
top.present(activityVC, animated: true, completion: nil)
}

Of course, it will need to be called in the touchesBegan method or a function. To share something, you will need to put it into the array that is in activityVC.

This isn't a share button, this is just the code that is used to share something to another app. You need to put it into a function or in touchesBegan and call it separately whenever you want to share something.



Related Topics



Leave a reply



Submit