How to use NSUserDefault with PickerView in Swift? - swift

I made some Labels that change using PickerView. But when I change the Label and if I run my app again, it doesn't save to selected one. So I have to use NSUserDefault but I don't know how to use it in right way.
This is my code:
var selectedFood = 0
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet var foodLabel: UILabel!
#IBOutlet var labelTwo: UILabel!
#IBOutlet var labelThree: UILabel!
#IBOutlet weak var foodPicker: UIPickerView!
var food = ["Bread", "Pizza", "Pasta", "Hot Dog", "Burger"]
#IBAction func submitLanguageButton(sender: AnyObject) {
if (selectedFood == 0) {
foodLabel.text = "Bread"
labelTwo.text = "Bread is a staple food prepared from a dough of flour and water..."
labelThree.text = "Bread is one of the oldest prepared foods..." // I used random information just as sample
}
else if (selectedFood == 1) {
foodLabel.text = "Pizza"
labelTwo.text = "Here will be more informations about Pizza"
labelThree.text = "A fact about Pizza" // I used random information just as sample
}
else if (selectedFood == 2) {
foodLabel.text = "Pasta"
labelTwo.text = "Here will be more informations about Pasta"
labelThree.text = "A fact about Pasta" // I used random information just as sample
}
else if (selectedFood == 3) {
foodLabel.text = "Hot Dog"
labelTwo.text = "Here will be more informations about Hot Dog"
labelThree.text = "A fact about Hot Dog" // I used random information just as sample
}
else if (selectedFood == 4) {
foodLabel.text = "Burger"
labelTwo.text = "Here will be more informations about Burger"
labelThree.text = "A fact about Burger" // I used random information just as sample
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
foodPicker.delegate = self
foodPicker.dataSource = self
if (selectedFood == 0) {
foodLabel.text = "Bread"
labelTwo.text = "Bread is a staple food prepared from a dough of flour and water..."
labelThree.text = "Bread is one of the oldest prepared foods..." // I used random information just as sample
}
else if (selectedFood == 1) {
foodLabel.text = "Pizza"
labelTwo.text = "Here will be more informations about Pizza"
labelThree.text = "A fact about Pizza" // I used random information just as sample
}
else if (selectedFood == 2) {
foodLabel.text = "Pasta"
labelTwo.text = "Here will be more informations about Pasta"
labelThree.text = "A fact about Pasta" // I used random information just as sample
}
else if (selectedFood == 3) {
foodLabel.text = "Hot Dog"
labelTwo.text = "Here will be more informations about Hot Dog"
labelThree.text = "A fact about Hot Dog" // I used random information just as sample
}
else if (selectedFood == 4) {
foodLabel.text = "Burger"
labelTwo.text = "Here will be more informations about Burger"
labelThree.text = "A fact about Burger" // I used random information just as sample
}
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return food[row]
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return food.count
}
public func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedFood = row
}
}
So when I choose Pizza, whenever I run my app I want to be it Pizza, if I select another one for example Pasta, I want to be that one Pasta.
Can you please help me ?

WBMDDrugManagerErrorCodeSave the selection like so:
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
NSUserDefaults.standardUserDefaults().setInteger(row, forKey: "choosenFood")
NSUserDefaults.standardUserDefaults().synchronize()
self.setLabelsForChoice(row)
}
Retrieve the chosen selection like so:
override func viewWillAppear() {
super.viewWillAppear()
if let previousSelection:Int = NSUserDefaults.standardUserDefaults().integerForKey("choosenFood") as? Int{
self.setLabelsForChoice(previousSelection)
}
}
Create a label update method similar to this:
func setLabelsForChoice(_choice:Int){
switch _choice{
case 0:
foodLabel.text = "Bread"
labelTwo.text = "Bread is a staple food prepared from a dough of flour and water..."
labelThree.text = "Bread is one of the oldest prepared foods..."
break
case 1:
foodLabel.text = "Pizza"
labelTwo.text = "Here will be more informations about Pizza"
labelThree.text = "A fact about Pizza"
break
default:
break
}
}

Related

Build a Dictionary Class with Static Data (Swift)

I need some help to build a Class that will serve as basis for all static content my app will use like States, Cities, Countries, Company classification among others. I'm not expecting those to change over time (or there would be very little change).
As a reference, I'll consider for now Countries and Cities (the logic would be the same for all others)
Class Country:
import UIKit
class Country {
var name: String
var cities: [City]
init(name:String, cities:[City]) {
self.name = name
self.cities = cities
}
}
Class City:
import UIKit
class City {
var name: String
init(name:String) {
self.name = name
}
}
In my existing code, I use the reference to those 2 classes but I feed the data in my ViewController.
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet weak var pickerView: UIPickerView!
#IBOutlet weak var countryLbl: UILabel!
var countries = [Country]()
override func viewDidLoad() {
super.viewDidLoad()
pickerView.delegate = self
pickerView.dataSource = self
// Adding Countries and Cities
countries.append(Country(name: "UK", cities: [City(name: "London"),City(name: "Manchester"), City(name: "Bristol")]))
countries.append(Country(name: "USA", cities: [City(name: "New York"),City(name: "Chicago")]))
countries.append(Country(name: "China", cities: [City(name: "Beijing"),City(name: "Shanghai"), City(name: "Shenzhen"), City(name: "Hong Kong")]))
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return countries.count
} else {
let selectedCountry = pickerView.selectedRow(inComponent: 0)
return countries[selectedCountry].cities.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
return countries[row].name
} else {
let selectedCountry = pickerView.selectedRow(inComponent: 0)
return countries[selectedCountry].cities[row].name
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
pickerView.reloadAllComponents()
let selectedCountry = pickerView.selectedRow(inComponent: 0)
let selectedCity = pickerView.selectedRow(inComponent: 1)
let cityR = countries[selectedCountry].cities[selectedCity].name
countryLbl.text = "The right answer was: in \(selectedCountry) in \(cityR)"
}
}
To make my code cleaner, I wanted to move code below to another class and call it from my ViewController
// Adding Countries and Cities
countries.append(Country(name: "UK", cities: [City(name: "London"),City(name: "Manchester"), City(name: "Bristol")]))
countries.append(Country(name: "USA", cities: [City(name: "New York"),City(name: "Chicago")]))
countries.append(Country(name: "China", cities: [City(name: "Beijing"),City(name: "Shanghai"), City(name: "Shenzhen"), City(name: "Hong Kong")]))
}
replaced by something like
let countriesAndCities = Dicitionary.getCountriesAndCities
// Here I would expect countriesAndCities to have the same content as countries.append(...) above.
Is this doable?
Thanks
As per rmaddy answer you can do your own json file by:
Creating your empty fil, save it as json file and in there you can paste the countries and cities.
Kindly see the code how I implement the pickerView in viewController..
If you can notice I print the "countryList" in my code below so I can check if the array of countriesJson is not empty. (Please check your logs)
Update for 2 components in pickerView.
enter image description here

How can I get value of a Dictionary item from first item of an Array in Swift?

I have defined Dictionary in an Array object below:
var dataList : [[String:Any]]?
And then I have loaded some data in to it. Here is the output when i run this code below:
print("DATA LIST:\n \(myRecordList)")
Output:
Optional([["itemCode": 0, "itemText": please select city], ["itemCode": 1, "itemText": City A], ["itemCode": 2, "itemText": City B], ["itemCode": 3, "itemText": City C], ["itemCode": 4, "itemText": City D], ["itemCode": 5, "itemText": City E], ["itemCode": 6, "itemText": City F]])
I would like to reach value of a dictionary from first item in an Array:
As you know, here is the first item in an array:
["itemCode": 0, "itemText": please select city]
And here is the value in above dictionary:
"itemText": please select city
After that I would like to set above text ("please select city") as a button title if dataList count is not zero:
if dataList?.count != 0
{
**//need help in here!!!**
{
self.btnSelectMarkaOutlet.setTitle(tempBtnTitle, for: .normal)
}
}
I have tried below scope. But it crushed:
if let newTry = dataList![0]["itemText"] as? [String]
{
print("here is the output:: \(newTry[0])")
}
Here is the error:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
let tempBtnTitle = must be "please select city"
I wanted to do this.
Let me share whole view controller file. Because dataList is nil.
import UIKit
class SinyalSeviyesineGoreAramaYapViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet weak var btnSelectMarkaOutlet: UIButton!
#IBOutlet weak var pickerViewOutlet: UIPickerView!
var dataList : [[String:Any]]?
override func viewDidLoad() {
print("viewDidLoad")
super.viewDidLoad()
self.pickerViewOutlet.delegate = self
self.pickerViewOutlet.dataSource = self
self.loadSayacRecordsForTheUIPickerView()
print("Is the data list nil? : \(self.dataList)")
if let newTry = self.dataList![0]["itemText"] as? String
{
print("here is the output:: \(newTry)")
}
//I WANTED TO SET BUTTON TITLE !!
let tempButtonTitle = ""
self.btnSelectMarkaOutlet.setTitle(tempButtonTitle, for: .normal)
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let recordName = self.dataList![row]
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
//return self.cityList![row]
let info = self.dataList![row]
if let name = info["itemCode"] as? String,
let code = info["itemText"] as? String
{
let text = "\(name) - \(code)"
//print("am i here? \(text)")
return text
}
return nil
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.dataList == nil ? 0 : self.dataList!.count
}
func loadSayacRecordsForTheUIPickerView()
{
print("loadSayacRecordsForTheUIPickerView method is called")
ServiceManager.oServiceManager.loadSayacRecords()
{
(result) in
if let sayacRecords = try? JSONSerialization.jsonObject(with: result!, options: .mutableContainers) as? [String:Any]
{
if let resultCodeFromWebApi = sayacRecords?["resultCode"] as? String
{
DispatchQueue.main.async
{
print("loadSayacRecordsForTheUIPickerView resultCode: \(resultCodeFromWebApi)")
if resultCodeFromWebApi == "999"
{
if let myRecordList = sayacRecords?["recordList"] as? [[String:Any]]
{
//DispatchQueue.main.async
//{
self.dataList = myRecordList
print("DATA LIST:\n \(self.dataList)")
self.pickerViewOutlet.reloadAllComponents()
//}
}
} // resultCodeFromWebApi == 999 ENDS
else
{
if let resultMessageFromWebApi = sayacRecords?["resultMessage"] as? String
{
print("resultMessage: \(resultMessageFromWebApi)")
}
}
} // DispatchQueue.main.async ENDS
}
else
{
print("cant parse it")
} // if let resultCodeFromWebApi = loginResult?["resultCode"] as? Int ENDS
}
}
} // loadSayacRecordsForTheUIPickerView ENDS
} // class SinyalSeviyesineGoreAramaYapViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource ENDS
The problem is in the logic you implemented: the dataList is loaded asynchronously, which means that you don't know when it will be available, but you are using it like it's always available.
Example of this error is in the viewDidLoad:
self.loadSayacRecordsForTheUIPickerView()
print("Is the data list nil? : \(self.dataList)")
if let newTry = self.dataList![0]["itemText"] as? String
{
print("here is the output:: \(newTry)")
}
With the first line you start to load the dataList, but in the for loop you are force unwrapping, which means you are saying "Ehi I'm 100% sure it will be available" - which is not true.
A possible solution for your problem is to convert the dataList! to dataList? everywhere, so if it's not loaded then nothing happens and your app won't crash.
A better and quicker solution is to have a default value for dataList, so in case is not loaded you will just react to an empty data model:
var dataList : [[String:Any]] = [[String:Any]]()
A reason would be array is nil and also you are unwrapping with [String] which is String, which may give nil.
Try below to avoid crashes.
if dataList?.isEmpty == false,let firstDic = dataList?.first, let neededString = firstDic["itemText"] as? String {
}

Assigning a different output value than what is shown on UIPickerView

I've searched all throughout yesterday on this website for an answer to this, but I haven't been able to find this. I'm an amateur coder, really just doing this for a small organization to see if we can help improve processes.
Here is what I'm trying to do. I'm trying to make an app that allows someone to select an account number, a task, and then it will output a numerical number for a full account number that they can put on receipts.
For example, someone selects account number 12345678910 and they select "cleaning the bathroom". I want the app to spit out a full account number like 12345678910 58392, where 58932 is associated with "cleaning the bathroom", but is not actually shown on the PickerView. I've been having trouble with this. Coding is something I've always wanted to learn, but have been doing it on my own time, so please forgive the amateur like mistakes if any. I've been using YouTube videos for this.
Any help is appreciated. Thanks so much!
Sample app screen-shot
import UIKit
class Account {
var account: String
var jlCode: [String]
init(account:String, jlCode:[String]) {
self.jlCode = jlCode
self.account = account
}
}
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet weak var pickerView: UIPickerView!
#IBOutlet weak var accountLbl: UILabel!
var accounts = [Account]()
#IBAction func showPopup(_ sender: Any) {
let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "sbPopUpID") as! PopUpViewController
self.addChildViewController(popOverVC)
popOverVC.view.frame = self.view.frame
self.view.addSubview(popOverVC.view)
popOverVC.didMove(toParentViewController: self)
}
override func viewDidLoad() {
pickerView.delegate = self
pickerView.dataSource = self
//This area will have to be changed once you get the right information.
accounts.append(Account(account: "12345678910", jlCode: ["task 1", "task 2", "task 3", "task 4"]))
accounts.append(Account(account: "1112131415", jlCode: ["Task 1"]))
accounts.append(Account(account: "1617181920", jlCode: ["task 1", "task 2", "task 3", "task 4"]))
accounts.append(Account(account: "2122232425", jlCode: ["task 1", "task 2", "task 3", "task 4"]))
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return accounts.count
} else {
let selectedAccount = pickerView.selectedRow(inComponent: 0)
return accounts[selectedAccount].jlCode.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
return accounts[row].account
} else {
let selectedAccount = pickerView.selectedRow(inComponent: 0)
return accounts[selectedAccount].jlCode[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
pickerView.reloadComponent(1)
let selectedAccount = pickerView.selectedRow(inComponent: 0)
let selectedjlCode = pickerView.selectedRow(inComponent: 1)
let account = accounts[selectedAccount].account
let jlCode = accounts[selectedAccount].jlCode[selectedjlCode]
accountLbl.text = "Account Number: \(account)\nJL Code: \(jlCode)"
}
}
If, and that is a big IF, I understand you correctly your problem is that you have nothing connecting the description of the task with the numeric value associated with the task. In other words it seems your simply struggling with the modelling of your data.
I would think something like the below might help you in the right direction:
struct Account {
var number: Int
var tasks: [Task]
var description: String { return "\(number)" }
}
struct Task {
var number: Int // or JLNumber, or whatever you want to call it
var description: String
}
That would leave you setting up Accounts like this:
let account = Account(number: 12345678910, tasks: [Task(number: 58932, description: "Cleaning the bathroom")])
You would display the .description in the pickerView, and use the .number wherever that makes sense.
If the different type of tasks are predefined, (i. e. they will never change without the code being changed) you should have a look at enums rather than creating them on the fly with strings and integers...

issues loading items from firebase to a pickerview

I have successfully created a QuestionModel class which retrieves items from firebase such, as a Question, string of answers and a correct question. I am however now having difficulty in terms of getting these items to go into a picker view from another class. The class called QuestionsViewController is where I am having an issue in terms of using the questions class to retrieve data from. The QuestionModel class contains retrieving data from firebase. I am having bad execution errors throughout the code in the QuestionsViewController class. This mainly occurs when trying to set the itemlabel text before the pickverview and code for the pickerview functions.
import Foundation
import Firebase
import FirebaseDatabase
import FirebaseAuth
import CoreData
class QuestionList
{
//properties
public static var Username: String = ""
private static var quiz = [Question]()
static func getDummyQuestions()->[Question]
{
//create some dummy data for the model
var ref: FIRDatabaseReference!
var refHandle: UInt!
ref = FIRDatabase.database().reference() //reference
refHandle = ref.child("Questions").child("Q1").observe(.value, with: { (snapshot)in
if let dataDict = snapshot.value as? [String: Any] {
if let quest = dataDict["Question"] as? String,
let Answers = dataDict["Answers"] as? [String],
let Correct = dataDict["Correct"] as? Int {
quiz.append(Question(q: quest, a: Answers, c: Correct))
}
print (dataDict)
}
})
return quiz
}
}
class Question {
var quest:String
var answers:[String]
var correct:Int
init(q: String, a:[String], c:Int)
{
quest = q
answers = a
correct = c
}
func isCorrectQuestion(itemSelected: String)->Bool {
if (itemSelected == answers[correct]) {
return true
} else {
return false
}
}
}
import UIKit
import Firebase
import FirebaseAuth
class QuestionsViewController: UIViewController, UIPickerViewDelegate {
#IBOutlet weak var usernamelabel: UILabel! //sets username label
#IBOutlet weak var Next: UIButton! //next button
#IBOutlet weak var itemLabel: UILabel! //item user has selected
#IBOutlet weak var Question: UILabel! //sets question label
#IBOutlet weak var pickerview: UIPickerView! //sets picker view
public var totalQuestions: Int = 0 //sets total question to 0
public var currentQuestion = 0 //sets current question to 0
public var totalCorrect: Int = 0 //sets totalcorrect to 0
var itemSelected: String = "" //item selected
var LabelText = String()
let Exam = QuestionList() //uses the questions class for instances
var Questions = QuestionList.getDummyQuestions()
var ref: FIRDatabaseReference!
var refHandle: UInt!
override func viewDidLoad() {
super.viewDidLoad() //when the app is loaded
ref = FIRDatabase.database().reference() //reference
refHandle = ref.child("Questions").observe(.value, with: { (snapshot)in
let dataDict = snapshot.value as! [String: AnyObject]
print (dataDict)
})
usernamelabel.text = LabelText //username
pickerview.delegate = self
itemLabel.text = "" //loads the item label of whats selected
itemSelected = QuestionList.getDummyQuestions()[currentQuestion].answers[0] //initially when loaded first item is selected
Question.text = QuestionList.getDummyQuestions()[currentQuestion].quest
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1 //return one component from the picker
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
return QuestionList.getDummyQuestions()[currentQuestion].answers.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{
return QuestionList.getDummyQuestions(). [currentQuestion].answers[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){
itemSelected = QuestionList.getDummyQuestions(). [currentQuestion].answers[row]
}
#IBAction func NextAction(_ sender: Any){
currentQuestion = currentQuestion + 1 //moves onto next question and increments
if (QuestionList.getDummyQuestions()[currentQuestion].isCorrectQuestion(itemSelected: itemSelected)) {
totalCorrect += 1
itemLabel.text = String(totalCorrect) + "/" + String(totalQuestions)
}
if(currentQuestion < QuestionList.getDummyQuestions().count) {
pickerview.reloadAllComponents()
itemSelected = QuestionList.getDummyQuestions()[currentQuestion].answers[1]
Question.text = QuestionList.getDummyQuestions() [currentQuestion].quest
} else {
pickerview.isHidden = true
Question.text = "You have finished"
Next.isHidden = true
}
}
}
Firebase functions do not (and should not) return values as they are asynchronous.
So the return quiz line will fail most of the time as it will try to return data before Firebase has had time to retrieve it from the server.
When coding with Firebase, data is only valid inside the closure following the function. So for example, this what NOT to do:
func someFunc() {
ref.child("Questions").child("Q1").observe(.value, with: { snapshot in
print(snap)
})
print(snap) //this will not print the snap as this line executes *before* the closure
}
So doing it the right way; retrieve the data from Firebase, populate the array and refresh the tableview all within the closure.
static func populateArrayAndRefreshTableView()
{
var ref: FIRDatabaseReference!= FIRDatabase.database().reference()
let questionsRef = ref.child("Questions")
questionsRef.child("Q1").observeSingleEvent(of: .value, with: { snapshot in
if let dataDict = snapshot.value as? [String: Any] {
let quest = dataDict["Question"] as? String,
let Answers = dataDict["Answers"] as? [String],
let Correct = dataDict["Correct"] as? Int {
self.quizArray.append(Question(q: quest, a: Answers, c: Correct))
self.tableView.reloadData()
}
})
}
}
Also note that the original code was using observe(.value). That will leave an observer attached to the ref and if the question changes, the code will be called. It doesn't look like that should be the behavior so using observeSingleEvent will call it once without adding an observer.
Finally - you may want to re-consider how the nodes are named in your structure. It's often best practice to disassociate node name keys from the data they contain.
questions
-UYiuokoksokda
question: "What significant contribution to bioengineering was made on the Loonkerian outpost on Klendth?"
correct_answer: answer_1
answers:
answer_0: "Left handed smoke shifter"
answer_1: "The universal atmospheric element compensator"
answer_2: "Warp coil nullification amplifier"
answer_3: "H.A.L. 9000"
-YY8jioijasdjd
question: "What is Kiri-kin-tha's first law of metaphysics?"
correct_answer: answer_2
answers:
answer_0: "No matter where you go, there you are"
answer_1: "Only people with sunroofs use them"
answer_2: "Nothing unreal exists"
answer_3: "Gravity is heavy"
The keys, UYiuokoksokda, are created with childByAutoId().
If you need to query answers you may want to even denormalize them into their own node and use the question key as the node key for the answers or keep a child node with the question key.

Swift app crashing without any errors?

I have an app in Swift. I have a view controller:
//
// ViewController.swift
// SwiftUIPickerFormatted
//
// Created by Codepixl
// Copyright (c) 2014
//
import UIKit
class FirstViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate,UIAlertViewDelegate {
#IBOutlet weak var chapterPicker: UIPickerView!
let chapterData = [1,2,3,4,5,6,7,8,9,10,11,12,13]
let lessonData = [1,2,3,4,5,6,7,8,9,10]
let classData = ["Pre Algebra","Algebra 1"]
var data = ["ade","01","01"]
override func viewDidLoad() {
super.viewDidLoad()
if(UIApplication.sharedApplication().canOpenURL(NSURL(string:"puffin://")!) == true){
println("Can open Puffin links")
}else{
showPuffinAlert()
}
chapterPicker.delegate = self
chapterPicker.dataSource = self
}
//MARK: - Delegates and datasources
//MARK: Data Sources
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 3
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if(component == 0){
return classData.count
}else if(component == 1){
return chapterData.count
}else if(component == 2){
return lessonData.count
}
return 1
}
//MARK: Delegates
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
if(component == 0){
return classData[row]
}else if(component == 1){
return "Chapter " + String(chapterData[row])
}else if(component == 2){
return "Lesson " + String(lessonData[row])
}
return "Error!"
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if(component == 0){
if(row == 0){
data[0] = "ade"
}else if(row == 1){
data[0] = "ate"
}
}else if(component == 1 || component == 2){
if(row+1 < 10){
data[component] = "0"+String(row+1)
}else{
data[component] = String(row+1)
}
}
println("puffin://www.phschool.com/webcodes10/index.cfm?wcprefix=\(data[0])&wcsuffix=\(data[1])\(data[2])&area=view")
}
func showPuffinAlert(){
var createAccountErrorAlert: UIAlertView = UIAlertView()
createAccountErrorAlert.delegate = self
createAccountErrorAlert.title = "Oops!"
createAccountErrorAlert.message = "It seems you do not have the Puffin web browser installed, which is required for this app to work. You can go ahead, but be aware the video and textbook links will not work."
createAccountErrorAlert.addButtonWithTitle("I understand- Proceed.")
createAccountErrorAlert.addButtonWithTitle("I'll download Puffin for free.")
createAccountErrorAlert.show()
}
func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){
switch buttonIndex{
case 0:
NSLog("Proceed");
break
case 1:
NSLog("DL");
UIApplication.sharedApplication().openURL(NSURL(string: "https://itunes.apple.com/us/app/puffin-academy/id716707933?mt=8#")!)
break
default:
NSLog("Default");
break
//Some code here..
}
}
#IBAction func GoVideo(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string:"puffin://www.phschool.com/webcodes10/index.cfm?wcprefix=\(data[0])&wcsuffix=\(data[1])\(data[2])&area=view")!)
}
}
And all works fine until I hit the "I understand-Proceed" or "I'll download Puffin for free" or the GoVideo button- it crashes with no error. I am completely stumped here as to what is happening...
EDIT: I have also cleared my build folder and manually deleted everything in it as well as adding a println in my app delegate and view controllers to make sure they have updated, and they have. Also the Simulator has been cleared.
There's probably a corrupted file in your Xcode project. Just make a new project and try the code there.