Saving an already implemented in game currency in Spritekit using swift - ios

I have an in game currency called diamonds, which are gained when a dragon runs into these diamonds, and they amount is added into a variable called diamondCount. I am using a label called diamondLabel to show the amount to the user, but I have tried alot of methods to save the diamonds when you close the game and none have worked for me. Can anyone please tell me a simple way to store diamonds(my in game currency) in gamescene.swift?

I've found the easiest way to save in game currency, granted you aren't trying to link it up to a backend service such as Parse, is by storing integer values into NSUserDefaults. Here is an example of how exactly you would be able to save the "diamonds."
Firstly, make a global variable in GameScene.swift called diamonds.
import Foundation
import UIKit
import SpriteKit
var diamonds = Int()
class GameScene: SKScene
{
override func viewMoveToView(view: SKView)
{
//Your game code here
}
}
This will make that integer variable accessible in all of your ViewControllers and SKScenes
Then you need to store your diamondCount at the end of a game into NSUserDefaults.
NSUserDefaults.standardUserDefaults().setInteger(diamondCount, forKey: "totalDiamonds")
Let me explain how the code line above works, when your gave is ended and you have a final integer value for diamondCount, then call that line of code to save the integer value of diamondCount into NSUserDefaults for the data to later be accessed through the reference key: "totalDiamonds"
Now to answer your questions about saving the diamonds after the player exits the game and comes back, I have written some code that you would put into your AppDelegate.swift.
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var oldDiamonds : Int = NSUserDefaults.standardUserDefaults().integerForKey("oldDiamonds");
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
diamonds += oldDiamonds
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication)
{
NSUserDefaults.standardUserDefaults().setInteger(diamonds, forKey: "oldDiamonds")
NSUserDefaults.standardUserDefaults().synchronize()
}
Hopefully you understand the end from what I've explained about NSUserDefaults. If you need any more information on it, please check Apple's Documentation on NSUserDefaults.
I hope this helps you! Comment any things I need to clarify.

Related

Swift 4 AppDelegate Thread 1: breakpoint 1.2 error

** i have gone through similar questions but havent been able to solve the problem..the error only occurs when i add any label or imageview but works fine when i change background color
any help will be greatly appreciated(stuck on this since evening). Thanks in advance!
hey guys I'm trying to build a simple ios project(fairly new to swift) and whenever i try to run my code in simulator i always get an error shown in the picture below. All i have done in this project so far is add a label and change background but when i run the code it shows succeeded but fails to run in any simulator and points me to the appdelegate.swift file Appdelegate Thread 1: breakpoint 1.2 error
This is my code:
AppDelegate.swift
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
viewcontroller.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
In my main.storyboard i have just added a label and changed background color
You've assumed this was an error but it's actually a debugging breakpoint. You inadvertently set a breakpoint which is easy to do. Where the line is green, it says breakpoint but does not say error.
To remove any breakpoints, click on the blue arrow seen in your screenshot. With the breakpoints removed, the code should run normally.
well, that just a debugging breakpoint is shown in the image If you have added breakpoints that is completely fine.
Either remove all breakpoints and try to run the program and check if it still stops there.
if you added an exceptional breakpoint then do this shown in the image below

how to make a IOS app with parse by AWS

all.
I want to make a IOS app with parse by AWS.
I watched [http://www.youtube.com/watch?v=sd2bphvVzGy][1]
this is Appdelegate.swift file.
import UIKit
import Parse
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let parseConfig = ParseClientConfiguration{ (ParseMutableClientConfiguration) in
ParseMutableClientConfiguration.applicationId = "myappid"
ParseMutableClientConfiguration.clientKey = "mymasterkey"
ParseMutableClientConfiguration.server = "http://ec2-13-124-93-153.ap-northeast-2.compute.amazonaws.com/parse"
// Override point for customization after application launch.
}
Parse.initialize(with: parseConfig)
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
I want to know how to get the information that "applicationId" and " Clientkey" from AWS. I cannot get the way to get the information at internet. anyone help me?
and if i run it.
there are wrong response.
2017-04-19 22:37:00.668 wanote[3667:493599] [Error]: unauthorized (Code: 0, Version: 1.12.0)
Optional(Error Domain=Parse Code=0 "unauthorized" UserInfo={error=unauthorized, NSLocalizedDescription=unauthorized, temporary=0})
Message from debugger: Terminated due to signal 15
could you teach me what is problem?
Best regards.

iOS Ignoring enqueueSampleBuffer because status is failed

When I restart app from here: https://github.com/zweigraf/face-landmarking-ios picture from camera doesn't appear and printing error: "Ignoring enqueueSampleBuffer because status is failed".
The problem is probably in captureOutput from SessionHandler.swift
I find a solution! Thanks to Why does AVSampleBufferDisplayLayer fail with Operation Interrupted (-11847)?
If you had similar problem you need to set AVSampleBufferDisplayLayer each time app entering foreground. Like this:
//AppDelegate.swift
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
viewcontroller?.setLayer()
}
//ViewController.swift
func setLayer() {
sessionHandler.layer = AVSampleBufferDisplayLayer()
sessionHandler.layer.frame = preview.bounds
sessionHandler.layer.videoGravity = AVLayerVideoGravityResizeAspectFill
preview.layer.addSublayer(sessionHandler.layer)
}
and don't forget to remove sublayer:
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
viewcontroller?.sessionHandler.layer.removeFromSuperlayer()
}

SkScene update method interrupted by push notifications, how can i detect the interruption

I have a simple game app, which is programmed with SpriteKit. The Problem is, when a push notifications (SMS,iMessage etc) appears, the game stutters because the update:forScene: method is not called.
To avoid this i want to implement a simple pause menu, which will be shown as soon as a push message comes in.
How can i detect if a push message interrupts the app? In AppDelegate application:willResignActive is also not called.
It would be the best if the game continues when the message comes in, if there is another solution to force the update method to be called.
Had anybody the same Problem?
You should not try to resume your game when an interruption is happening, you should pause it, otherwise its not a good user experience.
For iMessages, phone calls etc you usually use the method you said doesn't work.
I use NSNotificationCenter to pause my games, you can google about it, there is plenty tutorials.
Essentially in your game scene add a NSNotificationCenter observer.
Also create a property for that observers name to avoid typos later on.
let pauseGameKey = "PauseGameKey" // above class so you can access it anywhere in project
class GameScene: SKScene {
// add this in didMoveToView
// in #selector add the method you want to get called
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(yourPauseGameMethod), name: pauseGameKey, object: nil)
}
Than create the willMoveFromView method so you can remove the observer when you transition to another scene (good practice).
override func willMoveFromView(view: SKView) {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
Than in app delegate post the notification when the application will resign.
func applicationWillResignActive(application: UIApplication) {
NSNotificationCenter.defaultCenter().postNotificationName(pauseGameKey, object: nil)
}
For local and remote UINotifications you can additional use these 2 methods in app delegate.
/// Local notification
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
}
/// Remote notification
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
}
Hope this helps

How do you save global arrays in the applicationWillTerminate and reload them in the application function?

So I have been trying to make an app for my Mobile Apps Development class and I need to find a solution to a problem that I'm having when I save a global array called "events".
Here I tried to reload the saved event class in AppDelegate but it didn't change in the main screen view controller:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//Override point for customization after application launch.
//Load the events that were saved when application was terminated
let eventKey = NSUserDefaults.standardUserDefaults()
Global.events = (eventKey.arrayForKey("savedEvents") as? [Event])!
return true
}
Here is the function that is called when someone quits the app:
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
let myEvents = Global.events
NSUserDefaults.standardUserDefaults().setObject(myEvents, forKey: "savedEvents")
NSUserDefaults.standardUserDefaults().synchronize()
}
This might just be an error in the viewcontroller that displays this array but if you see something wrong with the code please let me know.
Two problems:
In iOS, there is no such thing as "someone quits the app", and thus what you're doing is unlikely to work, because applicationWillTerminate is never called. Save when the application is deactivated or backgrounded.
An array of Event cannot magically be saved in user defaults, because Event is not a Property List type. You will need to make Event archivable and archive the array.

Resources