在Xcode场景中集成Facebook和Twitter Swift iOS
我在Xcode中使用精灵套件和场景开发了一款游戏。现在我正在尝试整合功能,将高分发布到twitter和Facebook。我环顾四周,大多数人都说使用SLComposeServiceViewController这很好,直到我尝试并呈现它。因为我的应用程序确实只使用场景,所以它们从来没有成员函数“presentViewController(....)”。因此,我无法提供它。任何人都知道任何方式?在Xcode场景中集成Facebook和Twitter Swift iOS
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch:UITouch = touches.first!
let touchLocation = touch.location(in: self)
let touchedNode = self.atPoint(touchLocation)
if (touchedNode.name == "tryAgain") {
let nextScene = Scene_LiveGame(size: self.scene!.size)
nextScene.scaleMode = self.scaleMode
self.view?.presentScene(nextScene, transition: SKTransition.fade(withDuration: 0.5))
}
else if (touchedNode.name == "share") {
if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook) {
let fShare = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
self.presentViewController(fShare!, animated: true, completion: nil)
//^This is where my problem is. Xcode is telling me that self has no member function presentViewController which I totally understand, because its a scene and thus doesn't share those functions. But every resource online has shown me this is the only way to do it
}
}
我不会进入SLComposeViewController
相关的代码。除了crashoverride777提出的方法之外,我只会向您展示两种技术。因此,第一种技术是使用通知,像这样:
GameScene:
import SpriteKit
let kNotificationName = "myNotificationName"
class GameScene: SKScene {
private func postNotification(named name:String){
NotificationCenter.default.post(
Notification(name: Notification.Name(rawValue: name),
object: self,
userInfo: ["key":"value"]))
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.postNotification(named: kNotificationName)
}
}
在这里,您可以通过点击屏幕上张贴的通知。期望的视图控制器类可以侦听此通知,例如:
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(
self,
selector: #selector(self.handle(notification:)),
name: NSNotification.Name(rawValue: kNotificationName),
object: nil)
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = GameScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
}
}
func handle(notification:Notification){
print("Notification : \(notification)")
}
}
在这里,我们添加自作为该通知观察者 - 意味着,当通知发生时,一个适当的处理方法将被调用(这是我们的自定义handle(notification:)
方法。在这种方法中,你应该打电话给你的代码:
if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook) {
let fShare = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
self.presentViewController(fShare!, animated: true, completion: nil)
}
事实上,我会写的代表团另一个例子,保持干净的东西:)
,因为你需要从其他的UIViewController提出一个UIViewController您收到此错误。所以
self.presentViewController(...)
不会工作,因为自我(SKScene)不是UIViewController。从SKScene介绍,你会不得不说这
view?.window?.rootViewController?.presentViewController(fShare!, animated: true, completion: nil)
我建议你不要使用那些API了。更好地使用UIActivityViewController来满足您的共享需求。这样,您只需在应用程序中使用一个共享按钮,即可共享各种服务(电子邮件,Twitter,Facebook,iMessage,WhatsApp等)。
创建一个新的Swift文件并添加此代码。
enum ShareMenu {
static func open(text: String, image: UIImage?, appStoreURL: String?, from viewController: UIViewController?) {
guard let viewController = viewController, let view = viewController.view else { return }
// Activity items
var activityItems = [Any]()
// Text
activityItems.append(text)
// Image
if let image = image {
activityItems.append(image)
}
/// App url
if let appStoreURL = appStoreURL {
let items = ActivityControllerItems(appStoreURL: appStoreURL)
activityItems.append(items)
}
// Activity controller
let activityController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
// iPad settings
if UIDevice.current.userInterfaceIdiom == .pad {
activityController.modalPresentationStyle = .popover
activityController.popoverPresentationController?.sourceView = view
activityController.popoverPresentationController?.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
activityController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.init(rawValue: 0)
}
// Excluded activity types
activityController.excludedActivityTypes = [
.airDrop,
.print,
.assignToContact,
.addToReadingList,
]
// Present
DispatchQueue.main.async {
viewController.present(activityController, animated: true)
}
// Completion handler
activityController.completionWithItemsHandler = { (activity, success, items, error) in
guard success else {
if let error = error {
print(error.localizedDescription)
}
return
}
// do something if needed
}
}
}
// MARK: - Activity Controller Items
/**
ActivityControllerItems
*/
private final class ActivityControllerItems: NSObject {
// MARK: - Properties
/// App name
fileprivate let appName = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? "-"
/// App store web url
fileprivate let appStoreURL: String
// MARK: - Init
/// Init
fileprivate init(appStoreURL: String) {
self.appStoreURL = appStoreURL
super.init()
}
}
// MARK: - UIActivityItemSource
/// UIActivityItemSource
extension ActivityControllerItems: UIActivityItemSource {
/// Getting data items
/// Placeholder item
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return ""
}
/// Item for actity type
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivityType) -> Any? {
return URL(string: appStoreURL) ?? appName
}
/// Provide info about data items
/// Subject field for services such as email
func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivityType?) -> String {
return appName
}
}
当按下分享按钮比你可以把它像这样
ShareMenu.open(
text: "Can you beat my score?",
image: UIImage(...), // set to nil if unused
appStoreURL: "your iTunes app store URL", // set to nil if unused
from: view?.window?.rootViewController
)
记住,图像和appStoreURL不会出现遍地开花,这取决于共享服务。
您也可以从场景中使用你的分数值,并将它添加到文本e.g
ShareMenu.open(
text: "Can you beat my score \(self.score)?",
...
)
希望这有助于
是的,这也可能工作。 – Whirlwind
谢谢,我认为UIActivityControllers是共享的方式。你也只需要1个按钮。我也相信在某个地方看到那些共享API的人最终会被弃用,在这里我可能会完全错误。 – crashoverride777
我从来没有探索UIActivityControllers,但现在绝对会。谢谢你们,这明白了一大堆 – Matt
正如我所说的,这是可以使用的通知完成,像this answer,或者您可以与委托一起去:
首先,您应该声明MyDelegate
协议,该协议定义了一种名为myMethod()
的方法。
protocol MyDelegate:class {
func myMethod()
}
该方法是要求每个类必须实现,如果它符合这个协议。
在我们的例子中,你可以看看在现场为工人和视图控制器作为老板。场景完成任务后,它会通知老板(向他委派有关工作完成情况),以便老板可以决定下一步是什么。我的意思是,我可以说:“这个场景是一个老板,它将责任交给了他的员工,视图控制员......”但是,你认为谁是老板,并不重要...... delegation pattern很重要。
因此,视图控制器,应符合本协议,它会执行myMethod()
(将通过场景后来被称为):
class GameViewController: UIViewController, MyDelegate {
override func viewDidLoad() {
super.viewDidLoad()
//MARK: Conforming to MyDelegate protocol
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = GameScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
scene.myDelegate = self
// Present the scene
view.presentScene(scene)
}
}
}
func myMethod(){
print("Do your stuff here")
}
}
而且这里距离GameScene
代码,你定义myDelegate
的性质,我们用我们的视图控制器进行通信:
import SpriteKit
class GameScene: SKScene {
weak var myDelegate:MyDelegate?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.myDelegate?.myMethod()
}
}
要了解当选择了通知和代表团反之亦然看看this article(或只是搜索所以,有一些关于此的好帖子)。
谢谢,这确实有道理。比它做得更多。 – Matt
请发布您正在使用的代码(相关部分)。但通常,您可以在适当的视图控制器中指定视图控制器相关的方法,并在您想要调用这些方法时从场景发布通知。 – Whirlwind
来自'else if'块的代码应该替换为可以发布通知的代码。它也应该被移动到一个合适的视图控制器,该视图控制器有一个必需的成员方法并监听所提到的通知。 – Whirlwind
我不确定我是否遵循,我将代码移到了自定义视图控制器类,但是我仍然无法从我的场景中调用它。 – Matt