Reading UserDefault Values with swift - swift

I am trying to program a button to set a UserDefault to true. And when the view loads I want it to check if the value of the user default is true. If it is I want it to follow through with a line of code.
Here is my code:
import UIKit
import SpriteKit
import AVFoundation
var bombSoundEffect: AVAudioPlayer!
let instruct = UserDefaults.standard
class GameViewController: UIViewController {
#IBOutlet weak var intructions: UIButton!
#IBAction func intructions(_ sender: AnyObject) {
instruct.set(true, forKey: "instructions")
}
override func viewDidLoad() {
super.viewDidLoad()
if instruct.value(forKey: "instructions") {
intructions.isHidden = true
}
let path = Bundle.main.path(forResource: "Untitled2.wav", ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
bombSoundEffect = sound
sound.numberOfLoops = -1
sound.play()
} catch {
// couldn't load file :(
}
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .aspectFill
scene.size = self.view.bounds.size
skView.presentScene(scene)
}
}

Change
if instruct.value(forKey: "instructions")
to
if instruct.bool(forKey: "instructions")

Related

Camera View as blurred background?

I try to use my camera's view (blurred) as background in my main menu.
I'm a beginner and have no idea how to do this...
please don't answer with "use ARSCNView"; I've tried this.
(best: send me a code in swift; I shouldn't be too long huh?)
After trying your code I have these errors:
my code
import UIKit
import AVFoundation
class TestingViewController: UIViewController {
let session: AVCaptureSession = AVCaptureSession()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
session.sessionPreset = AVCaptureSession.Preset.high
if let device = AVCaptureDevice.default(for: AVMediaType.video) {
do {
try session.addInput(AVCaptureDeviceInput(device: device))
} catch {
print(error.localizedDescription)
}
let previewLayer = AVCaptureVideoPreviewLayer(session: session)
self.view.layer.addSublayer(previewLayer)
previewLayer.frame = self.view.layer.bounds
}
session.startRunning()
let blur = UIBlurEffect(style: .regular)
let blurView = UIVisualEffectView(effect: blur)
blurView.frame = self.view.bounds
blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(blurView)
}
}
try this updated code and dont forget to add
"Privacy - Camera Usage Description" in your info.plist file

Crashes with completion handler in GameViewController

Want to preload textureAtlases before game starts, so I decided to put scene starter code into completion handler, but for some reason app crashes. Here is my code:
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let gpuAtlas = SKTextureAtlas(named: "GP")
let ppAtlas = SKTextureAtlas(named: "PP")
SKTextureAtlas.preloadTextureAtlases([gpuAtlas, ppAtlas]) {
if let view = self.view as? SKView {
let scene = GameScene(size: self.view.bounds.size)
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
override var prefersStatusBarHidden: Bool {
return true
}
}
If I remove preload texture atlas method everything will work as usual, but I want preload textures to have a change to get rid of first keyframe freeze because of loading textures in cache.
Error:
fatal error: unexpectedly found nil while unwrapping an Optional value
Update:
It crashes on GameScene.swift file in method didSimulatePhysics.
What I do wrong guys?
Try this (use main thread for manipulation with view and weak self):
SKTextureAtlas.preloadTextureAtlases([gpuAtlas, ppAtlas]) { [weak self] in
guard let gameView = self?.view as? SKView else { return }
DispatchQueue.main.async {
let scene = GameScene(size: gameView.bounds.size)
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
gameView.presentScene(scene)
gameView.ignoresSiblingOrder = true
gameView.showsFPS = true
gameView.showsNodeCount = true
}
}
Did you check if scene is optional? If so:
guard let scene = GameScene(size: gameView.bounds.size) else { return }
This
let gpuAtlas = SKTextureAtlas(named: "GP")
let ppAtlas = SKTextureAtlas(named: "PP")
SKTextureAtlas.preloadTextureAtlases([GP, PP]) {}
should not compile - the variables are named gpuAtlas and ppAtlas and not GP and PP.

Could not cast value of type 'SCNView' to 'SKView'

I'm following a tutorial to create a "tetris" game in Swift with XCode 7. I followed every single step in this tutorial, but I'm getting a runtime error:
Could not cast value of type 'SCNView' (0x106c19778) to 'SKView' (0x1068fcad0).
My GameViewController.swift is as follows:
import UIKit
import SceneKit
import SpriteKit
class GameViewController: UIViewController {
var scene: GameScene!
var swiftris:Swiftris!
override func viewDidLoad() {
super.viewDidLoad()
//Configure the view
let skView = view as! SKView
skView.multipleTouchEnabled = false
//Create and configure the scene
scene = GameScene(size: skView.bounds.size)
scene.scaleMode = .AspectFill
scene.tick = didTick
swiftris = Swiftris()
swiftris.beginGame()
//Presente the scene.
skView.presentScene(scene)
scene.addPreviewShpaeToScene(swiftris.nextShape!){
self.swiftris.nextShape?.moveTo(StartingColumn, row: StartingRow)
self.scene.movePreviewShape(self.swiftris.nextShape!){
let nextShapes = self.swiftris.newShape()
self.scene.startTicking()
self.scene.addPreviewShpaeToScene(nextShapes.nextShape!) {}
}
}
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func didTick(){
swiftris.fallingShape?.lowerShapeByOneRow()
scene.redrawShape(swiftris.fallingShape!, completion: {})
}
}
I already search for it on google and here and I didn`t find anything related to SCNView and SKView.
Thank you in advance.
I did find the problem with my code. I instantiate the SKView as the view inside GameViewController:
self.view = SKView()
let skView = view as! SKView
Before I do that, I tried to change the class of the view to SKView in the storyboard, but it was not possible.
I'd like to thank you for the revisions.

Displaying interstitial admob when the game is over with Sprite Kit and iOS

I have been trying to display adds when the game is over for my game app. I have created a game over variable on GameScene.swift and I call that variable in the GameViewController.swift. However, the add is displayed shortly after the game starts. Could anyone point out what am I doing wrong? Here is my code:
import UIKit
import SpriteKit
import GoogleMobileAds
private var interstitial: GADInterstitial?
class GameViewController: UIViewController, GADInterstitialDelegate {
private var interstitial: GADInterstitial?
override func viewDidLoad() {
super.viewDidLoad()
interstitial = createInterstitial()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func prefersStatusBarHidden() -> Bool {
return true
}
private func createInterstitial() -> GADInterstitial {
let interstitial = GADInterstitial(adUnitID: "ca-app-pub-5713504307801022/7610056592")
interstitial.delegate = self
let request = GADRequest()
request.testDevices = ["ca-app-pub-5713504307801022/7610056592"]
interstitial.loadRequest(request)
return interstitial
}
func interstitialDidDismissScreen(ad: GADInterstitial!) {
interstitial = createInterstitial()
}
func interstitialDidReceiveAd(ad: GADInterstitial!) {
if (interstitial!.isReady) {
if gameOver1 == true {
self.interstitial!.presentFromRootViewController(self)
interstitial = createInterstitial()
}
}
}
}
First - this is how you should load and recycle AdMob interstitials -https://stackoverflow.com/a/37938286/2405378
Second - viewWillLayoutSubviews can be called multiple times and each time this method creates new instance of the GameScene - with gameOver1 being false?

How to add interstitial AdMob in iOS project with SpriteKit

I am trying to implement interstitial AdMob to my game app. But I have not had much luck so far. The code doesn't seem to have a bug but however it does not display the app. Any help would be much appreciate it. Thank you!
Here is my code:
import UIKit
import SpriteKit
import GoogleMobileAds
class GameViewController: UIViewController, GADInterstitialDelegate {
var interstitial: GADInterstitial!
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
interstitial = GADInterstitial(adUnitID: "ca-app-pub-5713504307801022/7610056592")
let request = GADRequest()
interstitial.loadRequest(request)
func CreateAD() -> GADInterstitial {
let interstital = GADInterstitial(adUnitID: "ca-app-pub-5713504307801022/7610056592")
interstitial.loadRequest(GADRequest())
return interstital
}
if gameOver == true {
if (interstitial.isReady){
interstitial.presentFromRootViewController(self)
interstitial = CreateAD()
}
}
}