In my GameViewController i have this function:
func shareButton(){
var myShare = "test"
let activityVC:UIActivityViewController = UIActivityViewController(activityItems: [myShare], applicationActivities: nil)
self.presentViewController(activityVC, animated: true, completion:nil)
}
I Want to call this function from my GameScene, I tried it like this but it won't work:
GameViewController.shareButton()
This gives the error: "Missing argument for parameter #1 in call"
What is the proper way to make this work?
In your game scene you can create a variable like this:
var gameViewController = GameViewController()
And then type this:
gameViewController.shareButton()
Related
I am transitioning between views programatically using the code below and it gets repeated quite a lot so I wanted to create a global function but I can't seem to be able to get the hang of it.
The code works when called inside a ViewController class, so I suppose the problem is that my function doesn't know which VC do I want to call navigationController.pushViewController on, but I don't know how to reference the VC either as an argument passed to the function, or better yet with something like .self to take the current VC class the function is called in.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "ExamplesControllerVC")
self.navigationController?.pushViewController(vc, animated: true)
The error I get if I try to run that as a function in a separate file is:
Use of unresolved identifier 'navigationController'; did you mean 'UINavigationController'?
So the function I'd like to create and call is something like:
showVC("ExamplesControllerVC")
Any ideas?
Whatever function this code is in needs to be updated to take a parameter of type UIViewController.
func showMain(on vc: UIViewController) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "ExamplesControllerVC")
vc.navigationController?.pushViewController(vc, animated: true)
}
Now you can call this as:
showMain(on: someViewController)
Or add this function to an extension on UIViewController then your use of self works just fine.
extension UIViewController {
func showMain() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "ExamplesControllerVC")
self.navigationController?.pushViewController(vc, animated: true)
}
}
Do you want to do something like this?:
extension UIViewController {
func presentView(withIdentifier: String) {
if let newVC = self.storyboard?.instantiateViewController(withIdentifier: withIdentifier) {
self.present(newVC, animated: true, completion: nil)
}
}
}
You can call it this way:
self.presentView(withIdentifier: "yourIdentifier")
Is it possible to have a function inside a completion handler?
I want to save an image through a function after the user shared that same image in activity controller.
I want to do the following:
let controller = UIActivityViewController(activityItems: [generateMemedImage()], applicationActivities: nil)
self.presentViewController(controller, animated: true, completion: nil)
controller.completionWithItemsHandler = {
// Have this save() function when the activity has been completed
func save() {
//Save the meme
let meme = Meme(topText: self.upperTextField.text!, lowerText: self.lowerTextField.text!, originalImage:
self.imageRetrieved.image!, memedImage: generateMemedImage())
}
}
Is there any better solution? Or how can I achieve this?
You don't need to declare a function inside the completion handler. Just write the code to perform the saving inside it, look
class Controller: UIViewController {
func foo() {
let controller = UIActivityViewController(activityItems: [generateMemedImage()], applicationActivities: nil)
self.presentViewController(controller, animated: true, completion: nil)
controller.completionWithItemsHandler = { activityType, completed, returnedItems, error -> () in
// write code to perform the save here <---
}
}
func generateMemedImage() -> [AnyObject] {
return []
}
}
I am trying to figure out how to use a share sheet for my SpriteKit game and when I try to present the view controller from my scene, it gives me an error.
if self.nodeAtPoint(location) == self.shareButton {
var tempMessage = "I just got \(score) on [insert app]"
let activityVC:UIActivityViewController = UIActivityViewController(activityItems: [tempMessage], applicationActivities: nil)
self.presentViewController(activityVC, animated: true, completion: nil)
}
This is in my GameOverScene. How exactly do you go about managing viewcontrollers in Swift because the answers I have seen were in OBJ-C.
Thanks!
Ok so I did some digging and found a solution that works.
Basically, I used NSNoticationCenter and set up the view controller in my GameViewController file as such.
override func viewDidLoad() {
.
.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "showSocialNetworks", name: "showSocialNetworksID", object: nil)
}
and made the function to be called
func showSocialNetworks(){
var tempMessage = "Insert your message to be shared on social network"
let activityVC:UIActivityViewController = UIActivityViewController(activityItems: [tempMessage], applicationActivities: nil)
self.presentViewController(activityVC, animated: true, completion: nil)
}
Now jump back to my GameOverScene, I set it up so when the user taps the Share Button, it performs the following code
if self.nodeAtPoint(location) == self.shareButton {
NSNotificationCenter.defaultCenter().postNotificationName("showSocialNetworksID", object: nil)
}
This may not be the cleanest way to do it, but it works for me. Hope this helps!
When a UIActivityViewController is called on the iPhone in this app, it works perfectly, but when called on a iPad, the app crashes. Below is the code I used:
func shareButtonPress() {
//when the share button is pressed, default share phrase is added, cropped image of highscore is added
var sharingItems = [AnyObject]()
var shareButtonHighscore = NSUserDefaults.standardUserDefaults().objectForKey("highscore") as Int!
sharingItems.append("Just hit \(shareButtonHighscore)! Beat it! #Swath")
UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, false, 0);
self.view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
sharingItems.append(image)
let activityViewController = UIActivityViewController(activityItems: sharingItems, applicationActivities: nil)
var barButtonItem: UIBarButtonItem! = UIBarButtonItem()
activityViewController.excludedActivityTypes = [UIActivityTypeCopyToPasteboard,UIActivityTypeAirDrop,UIActivityTypeAddToReadingList,UIActivityTypeAssignToContact,UIActivityTypePostToTencentWeibo,UIActivityTypePostToVimeo,UIActivityTypePrint,UIActivityTypeSaveToCameraRoll,UIActivityTypePostToWeibo]
self.presentViewController(activityViewController, animated: true, completion: nil)
}
As you can see, I'm programming in Swift, in the SpriteKit Framework, and I don't understand why the app is crashing.
I'm receiving this error:
Terminating app due to uncaught exception 'NSGenericException', reason: 'UIPopoverPresentationController (<_UIAlertControllerActionSheetRegularPresentationController: 0x7fc7a874bd90>) should have a non-nil sourceView or barButtonItem set before the presentation occurs.'
What can I do to fix this problem?
Before presenting the UIActivityViewController, add in this line of code:
activityViewController.popoverPresentationController?.sourceView = self.view
This way, the view controller knows in which frame of the GameViewController to appear in.
If you read the error it says how to fix it, you need to set the barButtonItem or sourceView from which to present the popover from, in your case:
func shareButtonPress(pressedButton: UIBarButtonItem) {
...
activityViewController.popoverPresentationController.barButtonItem = pressedButton
self.presentViewController(activityViewController, animated: true, completion: nil)
}
Swift 5:
Check if the device is iPhone or iPad and based on that add a sourceView and present the activityController
let activity = UIActivityViewController(activityItems: [self], applicationActivities: nil)
if UIDevice.current.userInterfaceIdiom == .phone {
UIApplication.topViewController?.present(activity, animated: true, completion: nil)
} else {
activity.popoverPresentationController?.sourceView = UIApplication.topViewController!.view
UIApplication.topViewController?.present(activity, animated: true, completion: nil)
}
There are two option, the action came from a UIBarButtonitem or UIButton that is a UIView.
func shareButtonPress() {
...
if let actv = activityViewController.popoverPresentationController {
actv.barButtonItem = someBarButton // if it is a UIBarButtonItem
// Or if it is a view you can get the view rect
actv.sourceView = someView
// actv.sourceRect = someView.frame // you can also specify the CGRect
}
self.presentViewController(activityViewController, animated: true, completion: nil)
}
You may have to add a sender to your function like func shareButtonPress(sender: UIBarButtonItem) or func shareButtonPress(sender: UIButton)
I added for Swift 3:
activityViewController.popoverPresentationController?.sourceView = self.view
fixed my issue.
I want to use this function in my GameScene:
func shareButton(){
var myShare = "test"
let activityVC:UIActivityViewController = UIActivityViewController(activityItems: [myShare], applicationActivities: nil)
self.presentViewController(activityVC, animated: true, completion:nil)
}
Because I am using a spritenode and when the spritenode is pushed, I want the sharebutton function to run. but as far as I know an UIActivitycontroller can not be in GameScene, only in GameViewController.
What is the proper way to do this?
Just use it in the GameViewController, no other way around.