Fatal Error: Index Out of Range(UIPickerView) - swift

I have a UIPickerView that is used to play the game Go Fish so data in it is continuously changing. AFter a few selections with the array I eventually get the error "Fatal Error: Index Out of Range" in the console and the error "thread 1 exc_bad_instruction (code=exc_i386_invop subcode=0x0)" on another line. Any idea on what is causing this and how to fix it.
Code:
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
///Main Section///
//Game
#IBOutlet weak var GameCardsLeft: UILabel!
//CPU
#IBOutlet weak var CPUCardsLeft: UILabel!
#IBOutlet weak var CPUPairs: UILabel!
//Player
#IBOutlet weak var UserPairs: UILabel!
#IBOutlet weak var pickerView: UIPickerView!
//Variables
var deck = [Card]()
//Creates a deck of cards
func createDeck() {
var i = 0 //Suite
while(i < 2) {
var s = "" //suite
var x = 1 //Value
if(i == 0) {
s = "Clubs"
}/* else if(i == 1) {
s = "Spades"
} else if(i == 2) {
s = "Diamonds"
}*/ else {
s = "Hearts"
}
while(x < 14) {
let tempCard = Card()
tempCard.value = x
tempCard.suite = s
tempCard.assignRank(value: tempCard.value)
tempCard.setDescription(rank: tempCard.rank, suite: tempCard.suite)
x += 1
deck.append(tempCard)
}
i += 1
}
}
//Shuffles the deck
func shuffle() {
var tempDeck = [Card]()
while deck.count > 0 {
let random = Int(arc4random_uniform(UInt32(deck.count)))
let card = deck.remove(at: random)
tempDeck.append(card)
}
deck = tempDeck
}
///Go Fish Section///
var drawDeck = [Card]()
var playerDeck = [Card]()
var playerPairsArray = [Card]()
var cpuDeck = [Card]()
var cpuPairsArray = [Card]()
var selectedCard = Card()
var gameOver = false
var randomIndex = 0
func deal() {
for card in deck {
if(playerDeck.count < 5) {
playerDeck.append(card)
} else if(cpuDeck.count < 5) {
cpuDeck.append(card)
} else {
drawDeck.append(card)
}
}
}
//Player draw card
func playerDraw() {
if(playerDeck.count == 0) {
while(playerDeck.count != 7) {
if(drawDeck.count > 0) {
playerDeck.append(drawDeck[0])
drawDeck.remove(at: 0)
} else {
break
}
}
} else {
if(drawDeck.count > 0) {
playerDeck.append(drawDeck[0])
drawDeck.remove(at: 0)
}
}
}
//CPU draw card
func cpuDraw() {
if(cpuDeck.count == 0) {
while(cpuDeck.count != 7) {
if(drawDeck.count > 0) {
cpuDeck.append(drawDeck[0])
drawDeck.remove(at: 0)
} else {
break
}
}
} else {
if(drawDeck.count > 0) {
cpuDeck.append(drawDeck[0])
drawDeck.remove(at: 0)
}
}
}
//Player's turn check cpu hand
func checkCPUHand(selectedCard: Card) {
var x = 0
while(x < cpuDeck.count) {
if(selectedCard.value == cpuDeck[x].value) {
playerDeck.append(cpuDeck[x])
cpuDeck.remove(at: x)
checkForPlayerPairs()
return
} else {
x += 1
}
}
playerDraw()
}
//CPU's turn check player hand
func checkPlayerHand(selectedCard: Card) {
var x = 0
while(x < playerDeck.count) {
if(selectedCard.value == playerDeck[x].value) {
cpuDeck.append(playerDeck[x])
playerDeck.remove(at: x)
checkForCPUPairs()
return
} else {
x += 1
}
}
cpuDraw()
}
//Check for player Pairs
func checkForPlayerPairs() {
var i = 0
var k = 0
var pairFound = false
while(i < playerDeck.count) {
pairFound = false
k = i + 1
while(k < playerDeck.count) {
if(playerDeck[i].value == playerDeck[k].value) {
pairFound = true
break
} else {
k += 1
}
}
if(pairFound) {
playerPairsArray.append(playerDeck[i])
playerDeck.remove(at: k)
playerDeck.remove(at: i)
} else {
i += 1
}
}
}
//Check for cpu pairs
func checkForCPUPairs() {
var i = 0
var k = 0
var pairFound = false
while(i < cpuDeck.count) {
pairFound = false
k = i + 1
while(k < cpuDeck.count) {
if(cpuDeck[i].value == cpuDeck[k].value) {
pairFound = true
break
} else {
k += 1
}
}
if(pairFound) {
cpuPairsArray.append(cpuDeck[i])
cpuDeck.remove(at: k)
cpuDeck.remove(at: i)
} else {
i += 1
}
}
}
/* Start of PickerView Stuff */
//Returns the number of columns
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
//Returns the number of rows
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return playerDeck.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return playerDeck[row].description //Error is in this line(thread 1 exc_bad_instruction (code=exc_i386_invop subcode=0x0))
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedCard = playerDeck[row]
//have var = pickerData[row]
}
/* End of PickerView Stuff */
func organizeCardDeck() {
playerDeck = playerDeck.sorted { $0.value < $1.value }
cpuDeck = cpuDeck.sorted { $0.value < $1.value }
}
func start() {
createDeck()
shuffle()
shuffle()
deal()
organizeCardDeck()
checkForPlayerPairs()
checkForCPUPairs()
GameCardsLeft.text = "\(drawDeck.count)"
CPUCardsLeft.text = "\(cpuDeck.count)"
CPUPairs.text = "\(cpuPairsArray.count)"
UserPairs.text = "\(playerPairsArray.count)"
}
func checkGameOver() {
if(cpuDeck.count == 0 && playerDeck.count == 0 && drawDeck.count == 0) {
let cpuPairCount = cpuPairsArray.count
let playerPairCount = playerPairsArray.count
playerDeck.removeAll()
cpuDeck.removeAll()
deck.removeAll()
cpuPairsArray.removeAll()
playerPairsArray.removeAll()
/*if(playerPairCount > cpuPairCount) {
let alertController = UIAlertController(title: "Game Over", message: "You win", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "Restart", style: .default, handler: nil)
alertController.addAction(defaultAction)
} else if(playerPairCount < cpuPairCount) {
let alertController = UIAlertController(title: "Game Over", message: "You lose", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "Restart", style: .default, handler: nil)
alertController.addAction(defaultAction)
} else if(playerPairCount == cpuPairCount) {
let alertController = UIAlertController(title: "Game Over", message: "Tie game", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "Restart", style: .default, handler: nil)
alertController.addAction(defaultAction)
}*/
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.pickerView.delegate = self
self.pickerView.dataSource = self
/*var alert = UIAlertController(title: "Go FIsh Go", message: "", preferredStyle: .alert)
var startAlert = UIAlertAction(title: "Start", style: .default, handler: nil)
alert.addAction(startAlert)
present(alert, animated: true, completion: nil)*/
start()
}
#IBAction func SelectCard(_ sender: UIButton) {
checkCPUHand(selectedCard: selectedCard)
checkForPlayerPairs()
pickerView.reloadAllComponents()
pickerView.selectRow(0, inComponent: 0, animated: true)
if(playerDeck.count == 0 && drawDeck.count > 0) {
playerDraw()
}
GameCardsLeft.text = "\(drawDeck.count)"
CPUCardsLeft.text = "\(cpuDeck.count)"
CPUPairs.text = "\(cpuPairsArray.count)"
UserPairs.text = "\(playerPairsArray.count)"
randomIndex = Int(arc4random_uniform(UInt32(cpuDeck.count)))
checkPlayerHand(selectedCard: cpuDeck[randomIndex])
checkForCPUPairs()
if(cpuDeck.count == 0 && drawDeck.count > 0) {
cpuDraw()
}
GameCardsLeft.text = "\(drawDeck.count)"
CPUCardsLeft.text = "\(cpuDeck.count)"
CPUPairs.text = "\(cpuPairsArray.count)"
UserPairs.text = "\(playerPairsArray.count)"
checkGameOver()
}
}

Change return playerDeck[row].description to: return (row < playerDeck.count ? playerDeck[row].description : nil), and change selectedCard = playerDeck[row] to:
if row < playerDeck.count {
self.selectedCard = playerDeck[row]
}
Also, call self.pickerView.reloadAllComponents() right before returning from your deal, playerDraw, checkCPUHand, checkPlayerHand, checkForPlayerPairs, organizeCardDeck, and checkGameOver functions, and any other functions that modify playerDeck.

Related

Can't update var value with text field value. Swift

I am creating an app for a project that determines whether or not a year is a leap year or not.
The overall logic itself is very simple, however I am trying to make it so when the button is pressed, it will take the value within the text field and then update var year with that value.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var guessLabel: UILabel!
#IBOutlet weak var guessTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func logic() {
// var year = guessTextField This is where the issue is.
var value1 = (year % 4)
var value2 = (year % 100)
var value3 = (year % 400)
var criteria: Bool!
print (value1)
print (value2)
criteria = false
func yearChecker() {
if value1 == 0 {
criteria = true
}
if value2 != 0, value1 == 0 {
criteria = true
}
if value3 == 0, value1 == 0 {
criteria = true
}
if criteria == true {
leapYearAlert()
}
if criteria == false {
showBoundsAlert()
}
}
}
#IBAction func submitButton(_ sender: UIButton) {
var year = guessTextField.text
logic()
}
func showBoundsAlert() {
let alert = UIAlertController(title: "Sorry, The Year You Chose is Not Special", message: "You're Year is Not a Leap Year:(", preferredStyle: .alert)
let action = UIAlertAction(title: "Okay", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
func leapYearAlert() {
let alert = UIAlertController( title: "Your Year is Special!", message: "The Year You Chose is in Fact a Leap Year!", preferredStyle: .alert)
let action = UIAlertAction(title: "Check For Another Year?", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
Cast year as Int because guessTextField.text return String.
#IBAction func submitButton(_ sender: UIButton) {
logic()
}
Change value1, value2, value3 from var to let as they don't change.
func logic() {
let year: Int = Int(guessTextField.text ?? "0")!
let value1: Int = (year % 4)
let value2: Int = (year % 100)
let value3: Int = (year % 400)
var criteria: Bool = false
print (value1)
print (value2)
if value1 == 0 {
criteria = true
}
if value2 != 0, value1 == 0 {
criteria = true
}
if value3 == 0, value1 == 0 {
criteria = true
}
if criteria == true {
leapYearAlert()
} else {
showBoundsAlert()
}
}

Saving HighScore in Swift 4

This code has all my labels Im trying to use. I can't save the High score and implement it into the game. Now its saying I need to type more so i'm just going to keep typing until it tells me i'm good. It still hasn't told me i'm goo i'm actually very surprised wow.
import UIKit
import CoreData
import SpriteKit
var timer:Timer?
var seconds:Int = 5
var maxSeconds: Int = 5
var totalPoints:Int = 0
var high:Int = 0
let userDefaults = UserDefaults.standard
let defaults = UserDefaults.standard
class ViewController: UIViewController {
#IBOutlet weak var menu: UIButton!
var i = 0
var point = 0
#IBOutlet weak var highScore: UILabel!
#IBOutlet weak var timeLabel:UILabel?
#IBOutlet weak var points:UILabel?
#IBOutlet weak var totalPoint: UILabel!
#objc func tapped(){
i += 1
switch i {
case 1:
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.error)
case 2:
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.success)
case 3:
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.warning)
case 4:
let generator = UIImpactFeedbackGenerator(style: .light)
generator.impactOccurred()
case 5:
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccurred()
case 6:
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.impactOccurred()
default:
let generator = UISelectionFeedbackGenerator()
generator.selectionChanged()
i = 0
}
}
func updateTimeLabel()
{
if(timeLabel != nil)
{
let sec:Int = seconds % 30
let sec_p:String = String(format: "%02d", sec)
timeLabel!.text = "\(sec_p)"
}
}
#objc func onUpdateTimer() -> Void
{
if(seconds > 0 && seconds <= maxSeconds)
{
seconds -= 1
updateTimeLabel()
}
else if(seconds == 0)
{
if(timer != nil)
{
timer!.invalidate()
timer = nil
userDefaults.set(totalPoints, forKey: "totalPoints")
let alertController = UIAlertController(title: "Time Up!", message: "Your time is up! You got a score of \(point) points and your total coins now is \(totalPoints). You Can Do Better", preferredStyle: .alert)
let restartAction = UIAlertAction(title: "Play Again!", style: .default, handler: nil)
alertController.addAction(restartAction)
let FirstSubview = alertController.view.subviews.first
let AlertContentView = FirstSubview?.subviews.first
for subview in (AlertContentView?.subviews)! {
subview.backgroundColor = UIColor(red: 226/255.0, green: 158/255.0, blue: 152/255.0, alpha: 5.0)
subview.layer.cornerRadius = 1
subview.alpha = 1
}
self.present(alertController, animated: true, completion: nil)
point = 0
seconds = maxSeconds
updateTimeLabel()
menu.isHidden = false
defaults.set(high, forKey: "high")
}
}
}
#IBAction func Restart(_ sender: Any) {
}
#IBAction func adder(_ sender: Any)
{
point += 1
points?.text = "\(point)"
if point % 10 == 0 {
totalPoints = 10 + totalPoints
totalPoint?.text = String(totalPoints)
}
if(timer == nil)
{
timer = Timer.scheduledTimer(timeInterval: 1.0, target:self, selector:#selector(onUpdateTimer), userInfo:nil, repeats:true)
}
tapped()
menu.isHidden = true
}
override func viewDidLoad() {
points?.text = "\(point)"
let total = userDefaults.integer(forKey: "totalPoints")
if total != 0 {
totalPoints = total
} else {
totalPoints = 0
}
let score = defaults.integer(forKey: "high")
if high < point {
high = score
} else {
high = 0
}
totalPoint?.text = String(totalPoints)
updateTimeLabel()
highScore.text = String(high)
}
}
Do I need to put something at the end? Well it looks like that didn't work either!
#for example
func saveHighScore() {
UserDefaults.standard.set(score, forKey: "HIGHSCORE")
}

Weather Swift Preferences

I'm currently working on an app with xCode, i'm new to iOS. My weather format is currently submitting "Celcius" & "Fahrenheit" to my database instead of sending C or F. I have try several thing but it seem to look like it also change my display text to C or F. I want to keep the display text to Fehrenheit & Celcius. Here's my code:
import UIKit
import FirebaseAuth
import FirebaseDatabase
class PreferencesVC: UIViewController, UITextFieldDelegate,
UIPickerViewDataSource, UIPickerViewDelegate {
#IBOutlet weak var setTimeFormat: UITextField!
#IBOutlet weak var setUnitFormat: UITextField!
#IBOutlet weak var setLanguage: UITextField!
var timePicker = UIPickerView()
var unitPicker = UIPickerView()
var languagePicker = UIPickerView()
var timeData: [String] = [String]()
var unitData: [String] = [String]()
var langugageData: [String] = [String]()
var preferenceHandle: DatabaseHandle!
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background4.png")!)
guard Auth.auth().currentUser != nil else {
print("TEST: No current user")
performSegue(withIdentifier: "LoginVC", sender: nil)
return
}
self.setTimeFormat.delegate = self
self.setUnitFormat.delegate = self
self.setLanguage.delegate = self
timeData = ["12 Hour","24 Hour"]
unitData = ["Celcius", "Fahrenheit"]
langugageData = ["English","Francais"]
timePicker.dataSource = self
timePicker.delegate = self
unitPicker.dataSource = self
unitPicker.delegate = self
languagePicker.dataSource = self
languagePicker.delegate = self
setTimeFormat.inputView = timePicker
setUnitFormat.inputView = unitPicker
setLanguage.inputView = languagePicker
setTimeFormat.text = "12 Hour"
setUnitFormat.text = "Fahrenheit"
setLanguage.text = "English"
let userID = User.uid
self.preferenceHandle = DataService.instance.userRef.child(userID).child("UserPreferences").observe(DataEventType.value, with: { (snapshot) in
if let userPreference = snapshot.value as? Dictionary<String, AnyObject> {
if let timeFormat = userPreference["UserTimeFormat"] as? String {
User.timeFormat = timeFormat
switch(timeFormat){
case "12H":
self.setTimeFormat.text = "12 Hour"
break;
case "24H":
self.setTimeFormat.text = "24 hour"
break;
default:
self.setTimeFormat.text = "12 Hour"
break;
}
}
if let unitFormat = userPreference["UserTempFormat"] as? String {
User.unitFormat = unitFormat
switch(unitFormat){
case "F":
self.setUnitFormat.text = "Fahrenheit"
break;
case "C":
self.setUnitFormat.text = "Celcius"
break;
default:
self.setUnitFormat.text = "Fahrenheit"
break;
}
}
if let language = userPreference["UserLanguage"] as? String {
print("language = " , language)
User.language = language
switch(language){
case "English":
self.setLanguage.text = "English"
break;
case "Français":
self.setLanguage.text = "Français"
break;
default:
self.setLanguage.text = "English"
break;
}
}
}
})
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func cancelButtonPressed(_ sender: Any) {
print("THEY PRESSED THE CANCEL BUTTON MASTER")
DataService.instance.userRef.child(User.uid).child("UserPreferences").removeObserver(withHandle: preferenceHandle)
dismiss(animated: true, completion: nil)
}
#IBAction func submitButtonPressed(_ sender: Any) {
print("THEY PRESSED THE SUBMIT BUTTON MASTER")
var userPreferences: Dictionary<String,String> = [:]
if (self.setTimeFormat != nil) && setTimeFormat.text != "" {
if let timeFormat = setTimeFormat.text {
switch(timeFormat){
case "24 Hour":
userPreferences["UserTimeFormat"] = "24H"
break;
case "12 Hour":
userPreferences["UserTimeFormat"] = "12H"
break;
default:
userPreferences["UserTimeFormat"] = "12H"
break;
}
}
}
if (self.setUnitFormat != nil) && setUnitFormat.text != "" {
if let unitFormat = setUnitFormat.text {
switch(unitFormat){
case "Fahrenheit":
userPreferences["UserTempFormat"] = "F"
break;
case "Celcius":
userPreferences["UserTempFormat"] = "C"
break;
default:
userPreferences["UserTempFormat"] = "F"
break;
}
userPreferences["UserTempFormat"] = unitFormat
}
}
if (self.setLanguage != nil) && setLanguage.text != "" {
if let language = setLanguage.text {
userPreferences["UserLanguage"] = language
}
}
DataService.instance.userRef.child(User.uid).child("UserPreferences").updateChildValues(userPreferences)
DataService.instance.userRef.child(User.uid).child("UserPreferences").removeObserver(withHandle: preferenceHandle)
User.timeFormat = setTimeFormat.text!
User.unitFormat = setUnitFormat.text!
User.language = setLanguage.text!
dismiss(animated: true, completion: nil)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
var count = 0
switch(pickerView){
case timePicker:
count = timeData.count
break
case unitPicker:
count = unitData.count
break
case languagePicker:
count = langugageData.count
break
default:
count = 0
break
}
return count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch(pickerView){
case timePicker:
return timeData[row]
case unitPicker:
return unitData[row]
case languagePicker:
return langugageData[row]
default:
return timeData[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch(pickerView){
case timePicker:
setTimeFormat.text = timeData[row]
break
case unitPicker:
setUnitFormat.text = unitData[row]
break
case languagePicker:
setLanguage.text = langugageData[row]
break
default:
setTimeFormat.text = timeData[row]
break
}
}
}
Remove this row in submitButtonPressed since it overrides what has been set just before
userPreferences["UserTempFormat"] = unitFormat

GADInterstitial presented too often

I am having problems with my interstitial ads popping up too often. The full screen ads comes on after every game over screen, meaning each time the player loses the ad pops up which i feel will get annoying. Is there a way to stop this happening after each failure to maybe after every 2 or 3 gameovers?
I have attached my code below, any help would be greatly appreciated.
import UIKit
import AVFoundation
import GoogleMobileAds
import Social
class ViewController: UIViewController {
#IBOutlet var bannerView: GADBannerView!
var admobInterstitial : GADInterstitial?
var timerAds : NSTimer?
var player:AVAudioPlayer = AVAudioPlayer()
var score = 0
var timer = NSTimer()
var seconds = 8
var watch = true
var watch1 = true
var gameActive = true
var hiScore = 0
var counter = 1
var turn = 0
var timer_anim = NSTimer()
#IBOutlet var btn: UIButton!
#IBOutlet var scr: UILabel!
#IBOutlet var scoreLabel: UILabel!
#IBOutlet var again: UIButton!
#IBOutlet var highScore: UILabel!
#IBOutlet var gameTimer: UILabel!
#IBOutlet var startView: UIImageView!
#IBOutlet var startButton: UIButton!
#IBOutlet var game_over: UIImageView!
#IBOutlet var twBtn: UIButton!
#IBAction func twitterBtn(sender: AnyObject) {
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter)
{
var twShare:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
twShare.setInitialText("I dare you get a higher score than mine : ( \(score) ) GET it NOW on IOS : https://itunes.apple.com/us/app/oscar-cookie/id1099453391?mt=8")
twShare.addImage(UIImage(named: "start.png"))
self.presentViewController(twShare, animated: true, completion: nil)
}
else
{
var alert = UIAlertController(title: "Account", message: "Please login to Twitter to Tweet", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
#IBOutlet var fbBtn: UIButton!
#IBAction func facebookBtn(sender: AnyObject) {
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook)
{
var fbShare:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
fbShare.setInitialText("I dare you get a higher score than mine : ( \(score) ) GET it NOW on IOS : https://itunes.apple.com/us/app/oscar-cookie/id1099453391?mt=8")
fbShare.addImage(UIImage(named: "start.png"))
self.presentViewController(fbShare, animated: true, completion: nil)
}
else
{
var alert = UIAlertController(title: "Account", message: "Please login to Facebook to share", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
#IBAction func startButtonFun(sender: AnyObject) {
startButton.hidden = true
startView.hidden = true
btn.hidden = false
player.pause()
}
#IBAction func playAgain(sender: AnyObject) {
player.pause()
//gameOverLbl.hidden = true
scoreLabel.hidden = true
again.hidden = true
btn.hidden = false
highScore.hidden = true
scr.hidden = false
game_over.hidden = true
fbBtn.hidden = true
twBtn.hidden = true
gameActive = true
watch = true
score = 0
scr.text = "0"
gameTimer.text = "8"
if watch1 == false
{
timer_anim.invalidate()
watch1 = true
}
}
#IBAction func button(sender: AnyObject) {
if score % 5 == 0
{
let audioPath = NSBundle.mainBundle().pathForResource("chew2", ofType: "mp3")!
do
{
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath : audioPath))
player.play()
}
catch
{
}
}
else
{
let audioPath = NSBundle.mainBundle().pathForResource("chew1", ofType: "mp3")!
do
{
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath : audioPath))
player.play()
}
catch
{
}
}
keepPlaying()
}
// func to locate the bottong randomly to all sizes
func randomLocating () {
var randomH = Int()
var randomW = Int()
if UIDevice().userInterfaceIdiom == .Phone {
switch UIScreen.mainScreen().nativeBounds.height {
case 480:
//print("iPhone Classic")
randomH = Int(arc4random_uniform(380))
randomW = Int(arc4random_uniform(260))
while randomH < 50 || randomW < 40
{
randomH = Int(arc4random_uniform(380))
randomW = Int(arc4random_uniform(260))
}
case 960:
//print("iPhone 4 or 4S")
randomH = Int(arc4random_uniform(380))
randomW = Int(arc4random_uniform(270))
while randomH < 50 || randomW < 40
{
randomH = Int(arc4random_uniform(380))
randomW = Int(arc4random_uniform(270))
}
case 1136:
// print("iPhone 5 or 5S or 5C")
randomH = Int(arc4random_uniform(520))
randomW = Int(arc4random_uniform(300))
while randomH < 40 || randomW < 40
{
randomH = Int(arc4random_uniform(520))
randomW = Int(arc4random_uniform(300))
}
case 1334:
// print("iPhone 6 or 6S")
randomH = Int(arc4random_uniform(550))
randomW = Int(arc4random_uniform(300))
while randomH < 35 || randomW < 40
{
randomH = Int(arc4random_uniform(550))
randomW = Int(arc4random_uniform(300))
}
case 2208:
// print("iPhone 6+ or 6S+")
randomH = Int(arc4random_uniform(700))
randomW = Int(arc4random_uniform(350))
while randomH < 40 || randomW < 40
{
randomH = Int(arc4random_uniform(700))
randomW = Int(arc4random_uniform(350))
}
default:
print("unknown")
}
}
else if UIDevice().userInterfaceIdiom == .Pad {
switch UIScreen.mainScreen().nativeBounds.height {
case 1024:
//print("iPad Classic")
randomH = Int(arc4random_uniform(950))
randomW = Int(arc4random_uniform(700))
while randomH < 50 || randomW < 40
{
randomH = Int(arc4random_uniform(950))
randomW = Int(arc4random_uniform(700))
}
case 2048:
//print("iPad Retina")
randomH = Int(arc4random_uniform(700))
randomW = Int(arc4random_uniform(350))
while randomH < 100 || randomW < 100
{
randomH = Int(arc4random_uniform(700))
randomW = Int(arc4random_uniform(350))
}
default:
print("unknown")
}
}
btn.frame.origin = CGPoint(x: randomW, y: randomH)
}
// func to end the game when someone loses
func endGame() {
btn.hidden = true
scoreLabel.text = "\(score)"
if hiScore < score
{
hiScore = score
highScore.text = "\(hiScore)"
}
else
{
highScore.text = "\(hiScore)"
}
NSUserDefaults.standardUserDefaults().setObject(hiScore, forKey: "high")
scoreLabel.hidden = false
again.hidden = false
highScore.hidden = false
scr.hidden = true
game_over.hidden = false
fbBtn.hidden = false
twBtn.hidden = false
let audioPath = NSBundle.mainBundle().pathForResource("end", ofType: "mp3")!
do
{
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath : audioPath))
player.play()
}
catch
{
}
}
func animating()
{
if counter < 5
{
counter += 1
}
startView.image = UIImage(named: "start-\(counter).png")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//gameOverLbl.hidden = true
scoreLabel.hidden = true
again.hidden = true
highScore.hidden = true
btn.hidden = true
game_over.hidden = true
game_over.hidden = true
fbBtn.hidden = true
twBtn.hidden = true
if watch1 == true
{
timer_anim = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("animating"), userInfo: nil, repeats: true)
watch1 = false
}
if NSUserDefaults.standardUserDefaults().objectForKey("high") != nil
{
var returnHigh = NSUserDefaults.standardUserDefaults().objectForKey("high") as! Int
hiScore = returnHigh
}
else
{
}
let audioPath = NSBundle.mainBundle().pathForResource("start", ofType: "mp3")!
do
{
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath : audioPath))
player.play()
}
catch
{
}
self.bannerView.adUnitID = "ca-app-pub-8964973200415729/4584433890"
self.bannerView.rootViewController = self
var request:GADRequest = GADRequest()
self.bannerView.loadRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/// to make the screen not rotate
override func shouldAutorotate() -> Bool {
return false
}
func keepPlaying()
{
score += 1
scr.text = "\(score)"
randomLocating()
if score < 5
{
seconds = 8
}
else
{
seconds = 5
}
if watch == true
{
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("click1"), userInfo: nil, repeats: true)
}
watch = false
gameTimer.text = "\(seconds)"
}
func click1 ()
{
gameTimer.text = "\(seconds)"
if seconds == 0 && gameActive == false
{
timer.invalidate()
endGame()
btn.hidden = true
turn += 1
if turn == 1
{
admobInterstitial = createAndLoadInterstitial()
timerAds = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("presentInterstitial"), userInfo: nil, repeats: false)
turn = 0
}
}
else if seconds == 1
{
btn.hidden = true
gameActive = false
}
else
{
btn.hidden = false
}
seconds -= 1
}
func createAndLoadInterstitial()->GADInterstitial {
var interstitial = GADInterstitial(adUnitID: "ca-app-pub-8964973200415729/8720255492")
///interstitial.delegate = self
interstitial.loadRequest(GADRequest())
return interstitial
}
func presentInterstitial() {
if let isReady = admobInterstitial?.isReady {
admobInterstitial?.presentFromRootViewController(self)
}
}
func interstitial(ad: GADInterstitial!, didFailToReceiveAdWithError error: GADRequestError!) {
print("interstitialDidFailToReceiveAdWithError:\(error.localizedDescription)")
admobInterstitial = createAndLoadInterstitial()
}
}
Simply change your turn counter. Instead of if turn == 1 change it to something else. Want an ad every 3 gameovers? Change it to 3. For example:
turn = turn + 1
if turn == 3 {
admobInterstitial = createAndLoadInterstitial()
timerAds = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: #selector(ViewController.presentInterstitial), userInfo: nil, repeats: false)
turn = 0
}

Swift: UIRefreshControl does not pull through when dragging down

I have a working UITableView in which I added a UIRefreshControl like this:
var refresher: UIRefreshControl!
...
// this is ViewDidLoad()
// pull to refresh
refresher = UIRefreshControl()
refresher.tintColor = globalClass.blue
refresher.attributedTitle = NSAttributedString(string: "")
refresher.addTarget(self, action: "loadFriends", forControlEvents: UIControlEvents.ValueChanged)
friendTableView.addSubview(refresher)
This works well on other UITableViews, but not on this one for some reason. The spinner never really spins and just snaps to the top when the dragging stops. What could cause this?
EDIT: loadFriends function
//load friends
func loadFriends() {
globalClass.requestsIn = []
globalClass.requestsOut = []
globalClass.finalSections = []
globalClass.myFriends = []
finalSections = []
sectionsG1 = []
let queryIn1 = PFQuery(className:"Friendship")
queryIn1.whereKey("toUser", equalTo: PFUser.currentUser()!.username!)
let queryOut = PFQuery(className:"Friendship")
queryOut.whereKey("fromUser", equalTo: PFUser.currentUser()!.username!)
let query = PFQuery.orQueryWithSubqueries([queryIn1, queryOut])
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if objects!.count == 0 {
self.friendtTableView.reloadData()
self.text()
} else {
for object in objects! {
let toUser:String = object["toUser"] as! String
let status:String = object["status"] as! String
if toUser == PFUser.currentUser()?.username {
if status == "pending" {
globalClass.requestsIn.append(object["fromUser"] as! String)
self.update()
} else if status == "approved" {
globalClass.myFriends.append(object["fromUser"] as! String)
globalClass.myFriends = globalClass.myFriends.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
self.update()
}
} else { if status == "pending" || status == "rejected" {
globalClass.requestsOut.append(object["toUser"] as! String)
self.update()
} else if status == "approved" {
globalClass.myFriends.append(object["toUser"] as! String)
globalClass.myFriends = globalClass.myFriends.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
self.update()
}
}
}
}
if self.tableSegment == 1 {
if globalClass.requestsIn.count == 0 {
self.friendTableView.reloadData()
self.text()
} else {
}
} else if self.tableSegment == 2 {
if globalClass.requestsOut.count == 0 {
self.friendTableView.reloadData()
self.text()
} else {
}
} else if self.tableSegment == 0 {
if globalClass.myFriends.count == 0 {
self.friendTableView.reloadData()
self.text()
} else {
}
}
self.refresher.endRefreshing()
} else {
}
}
}