enabling button in swift code - ios

I begin swift and i'm making an app ( a little game).
The buttons of levels 2,... are not enabled because the user dont yet win the level 1 when the user install the application. then I want these buttons enabled everytime the user won the level. I wrote this in a file:
class levelList: UIViewController {
#IBOutlet var blvl1: UIButton!
#IBOutlet var blvl2: UIButton!
#IBOutlet var blvl3: UIButton!
var lvlWon1: Bool = false {
didSet {
blvl2?.enabled = lvlWon1
}
}
var lvlWon2: Bool = false {
didSet {
blvl3?.enabled = lvlWon2
}
}
let lvl1Default = NSUserDefaults.standardUserDefaults()
let lvl2Default = NSUserDefaults.standardUserDefaults()
override func viewDidLoad() {
if (lvl1Default.objectForKey("lvlWon1") != nil){
lvl1Default.setBool(true, forKey: "lvlWon1")
lvlWon1 = lvl1Default.valueForKey("lvlWon1") as! Bool!
}
else{
lvl1Default.setBool(false, forKey: "lvlWon1")
lvlWon1 = lvl1Default.valueForKey("lvlWon1") as! Bool!
}
//
if (lvl2Default.objectForKey("lvlWon2") != nil){
lvl2Default.setBool(true, forKey: "lvlWon2")
lvlWon2 = lvl2Default.valueForKey("lvlWon2") as! Bool!
}
else{
lvl2Default.setBool(false, forKey: "lvlWon2")
lvlWon2 = lvl2Default.valueForKey("lvlWon2") as! Bool!
}
}
}
and this in an other file:
class lvl1: UIViewController {
var levelList = levelList()
#IBOutlet var bNext: UIButton!
#IBAction func nextlvl(sender: UIButton) {
levelList.lvlWon1 = true
levelList.lvlWon1 = levelList.lvl1Default.valueForKey("lvlWon1") as! Bool!
let lvl1Default = NSUserDefaults.standardUserDefaults()
lvl1Default.setValue(listeNiveaux.lvlWon1, forKey:"lvlWon1")
lvl1Default.synchronize()
}
//my problem is that all work finely when I wrote:
var lvlWon1: Bool = false {
didSet {
blvl2?.enabled = lvlWon1
}
}
so when i won the lvl 1, the level2 button is enabled, but when i add
var lvlWon2: Bool = false {
didSet {
blvl3?.enabled = lvlWon2
}
}
when I win the level1, the blvl2 and the blvl3 are enabled, I don't know why
I think it's because i save the data of all blvl but i'm not sure.
thanks in advance and really sorry for my english, it's not my first language.

The problem is because you are calling NSUserDefaults.standardUserDefaults() twice, in order to fix it you could:
Create a new variable named defaults and store the user defaults instance, so that this let lvl1Default = NSUserDefaults.standardUserDefaults()
let lvl2Default = NSUserDefaults.standardUserDefaults() becomes let defaults = NSUserDefaults.standardUserDefaults()
Use that new variable replacing the previous lvl1Default and lvl2Default on viewDidLoad (and do not forget to call super)
override func viewDidLoad() {
super.viewDidLoad()
if (defaults.objectForKey("lvlWon1") != nil){
defaults.setBool(true, forKey: "lvlWon1")
lvlWon1 = defaults.valueForKey("lvlWon1") as! Bool
}
else{
defaults.setBool(false, forKey: "lvlWon1")
lvlWon1 = defaults.valueForKey("lvlWon1") as! Bool
}
//
if (defaults.objectForKey("lvlWon2") != nil){
defaults.setBool(true, forKey: "lvlWon2")
lvlWon2 = defaults.valueForKey("lvlWon2") as! Bool
}
else{
defaults.setBool(false, forKey: "lvlWon2")
lvlWon2 = defaults.valueForKey("lvlWon2") as! Bool
}
}
Edit after 2016-08-10 comment:
On my first attempt to provide an answer to your problem, I tried to isolate the problem and I succesfully managed to recreate it without considering the code on the lvl1 class. Since this did not solved your issue, I made a second attempt taking the nextlvl function in consideration.
On this function, there is another NSUserDefaults.standardUserDefaults() call. The first thing I would do is to make the 'defaults' constant (explained previously) as a global variable so that you can access it everywhere. (in case you need more info about this, you could check this answer)
Another thing I noticed is the call to synchronize() which is deprecated.
So, after moving the defaults constant to somewhere global, I think what you meant to do on the nextlvl function should be:
#IBAction func nextlvl(sender: UIButton) {
lvlWon1 = true
defaults.setBool(true, forKey: "lvlWon1");
}
Edit 2:
As a side note:
When you are casting lvlWon2 = defaults.valueForKey("lvlWon2") as! Bool! you do not need to place ! in the type, as in as! Bool! you just need as! Bool
Bool is a boolean type that cannot be null whereas Bool! means a boolean type that is implicitly unwrapped and Bool? means a boolean type needs to be unwrapped.
If you wish to read more about wrappers, check The Swift Programming Language reference
You can also use defaults.boolForKey("lvlWon2") which gives you the result as a Bool type and avoid the casting.

I finally found the solution :
import UIKit
class ViewController: UIViewController {
var defaults = NSUserDefaults.standardUserDefaults()
#IBOutlet weak var startSecondLevelButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.checkLevelsStatuses()
}
func checkLevelsStatuses() {
startSecondLevelButton.enabled = false
if let lvlWon1 = defaults.objectForKey("lvlWon1") as? Bool {
// if true - level finished
if (lvlWon1) {
startSecondLevelButton.enabled = true
}
}else {
defaults.setBool(false, forKey: "lvlWon1")
}
if let lvlWon2 = defaults.objectForKey("lvlWon2") as? Bool {
} else {
defaults.setBool(false, forKey: "lvlWon2")
}
}
that was because the viewDidLoad was wrong.

Related

How to persist email and password textfield info using UserDefaults if checkbox is selected Swift iOS

I'm using BEMCheckBox library for checkbox.
The thing is when checkbox is true it doesn't save the inputs from the users
What I tried to do is when checkbox == true
it should,
save email and password and and set checkbox to true, then save it to user default.
if == false
should delete everything (email, password and reset checkbox to false).
, but it's not working.
var Defaults = UserDefaults.standard
#IBOutlet weak var box1: BEMCheckBox!
struct keys {
static let emailKey = "emailTextField"
static let passwordKey = "passwordTextField"
static var boxBool = "boxBool"
}
override func viewDidLoad() {
didTap(box1)
box1.delegate = self
checkSavedData()
}
func didTap(_ checkBox: BEMCheckBox) {
if checkBox.on == true {
rememberMyEmailandPassword()
} else if checkBox.on == false {
Defaults.removeObject(forKey: keys.emailKey)
Defaults.removeObject(forKey: keys.passwordKey)
Defaults.removeObject(forKey: keys.boxBool)
}
}
func rememberMyEmailandPassword() {
Defaults.set(emailTextField.text, forKey: keys.emailKey)
Defaults.set(passwordTextField.text, forKey: keys.passwordKey)
Defaults.set(box1.on, forKey: keys.boxBool)
}
func checkSavedData() {
let email = Defaults.value(forKey: keys.emailKey) as? String ?? ""
let password = Defaults.value(forKey: keys.passwordKey) as? String ?? ""
let boxBoolean = Defaults.bool(forKey: keys.boxBool)
emailTextField.text = email
passwordTextField.text = password
box1.on = boxBoolean
}
I think the problem with boxBoolean. because I believe boxBoolean doesn't recall the data again.
Thnx.
var defaults = UserDefaults.standard
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var box1: BEMCheckBox!
enum Keys: String {
case email, password, box1
}
override func viewDidLoad() {
// 1) loads the checkBox state when the view loads
box1.on = defaults.bool(forKey: Keys.box1.rawValue)
box1.delegate = self
// 2) update the UI in case it is checked
if box1.on {
loadData()
}
// 3) adds a control event for editing changed to both fields
emailTextField.addTarget(self, action: #selector(saveData), for: .editingChanged)
passwordTextField.addTarget(self, action: #selector(saveData), for: .editingChanged)
}
func didTap(_ checkBox: BEMCheckBox) {
// 4) saves the checkbox state
defaults.set(box1.on, forKey: Keys.box1.rawValue)
// 5) Saves field data or remove it
if box1.on {
defaults.set(emailTextField.text!, forKey: Keys.email.rawValue)
defaults.set(passwordTextField.text!, forKey: Keys.password.rawValue)
} else {
// 6) You should NEVER remove the checkbox value
defaults.removeObject(forKey: Keys.email.rawValue)
defaults.removeObject(forKey: Keys.password.rawValue)
}
}
#objc func saveData(_ textField: UITextField) {
// 7) update the data as the user types it in case it is checked
if box1.on {
defaults.set(emailTextField.text!, forKey: Keys.email.rawValue)
defaults.set(passwordTextField.text!, forKey: Keys.password.rawValue)
}
}
func loadData() {
// 8) updates the UI with the persisted data
// Note that text property is optional so you can pass an optional string (no need to unwrap it)
emailTextField.text = defaults.string(forKey: Keys.email.rawValue)
passwordTextField.text = defaults.string(forKey: Keys.password.rawValue)
}

Userdefaults to save switch state

I Have a switch that when turned to "on" will put the music and when the switch is set to "off" the music will resume playing. My problem is that when i leave the view controller the switch will appear as "off" when it is switch "on". The code for my switch is below, I'm not sure what to write in order for the app to remember the switch state, please help.
//
// SecondViewController.swift
// Urban Sphere
//
// Created by Oren Edrich on 9/11/16.
// Copyright © 2016 Oren Edrich. All rights reserved.
//
import Foundation
import UIKit
import SpriteKit
import AVFoundation
var bombSoundEffect: AVAudioPlayer!
var Ghost = SKSpriteNode()
class SecondViewController: UIViewController {
var sw = false
#IBOutlet var mySwitch: UISwitch!
#IBAction func switchpressed(_ sender: AnyObject) {
if mySwitch.isOn{
if bombSoundEffect != nil {
bombSoundEffect.stop()
bombSoundEffect = nil
}
}
else{
let path = Bundle.main.path(forResource: "newmusic.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 :(
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
I found the correct answer and decided to post it incase anyone has the same question.
#IBAction func saveSwitchState(sender: AnyObject) {
var defaults = NSUserDefaults.standardUserDefaults()
if bluetoothSwitch.on {
defaults.setBool(true, forKey: "SwitchState")
} else {
defaults.setBool(false, forKey: "SwitchState")
}
}
and...
override func viewDidLoad() {
super.viewDidLoad()
var defaults = NSUserDefaults.standardUserDefaults()
if (defaults.objectForKey("SwitchState") != nil) {
bluetoothSwitch.on = defaults.boolForKey("SwitchState")
}
}
You want know where to insert the code , I guess.
updata
updata2
Then you can run directly. If it's useful , please UP this answer.
import Foundation
import UIKit
import SpriteKit
import AVFoundation
class SecondViewController: UIViewController {
static let bombSoundEffect = {()->(AVAudioPlayer) in
let path = Bundle.main.path(forResource: "newmusic.wav", ofType:nil)!
let url = URL(fileURLWithPath: path)
return try! AVAudioPlayer(contentsOf: url)
}()
var sw = false
var Ghost = SKSpriteNode()
#IBOutlet var mySwitch: UISwitch!
#IBAction func switchpressed() {
if mySwitch.isOn{
SecondViewController.bombSoundEffect.play()
}else{
SecondViewController.bombSoundEffect.stop()
}
//************* save status *************
UserDefaults.standard.set(mySwitch.isOn, forKey: "SwitchStatus");
}
override func viewDidLoad() {
super.viewDidLoad()
mySwitch.addTarget(self, action: #selector(switchpressed), for: .valueChanged)
//************* load status *************
mySwitch.isOn = UserDefaults.standard.bool(forKey: "SwitchStatus");
switchpressed()
}
}
I have a similar situation to yours, and I just use UserDefaults. Here's a step-by-step guide on how to do it.
Create a variable like the following example. This will set the default setting and store the state of the check box for use later:
var musicSetting = UserDefaults().string(forKey: "Music") ?? "On"
In your viewDidLoad, add an if statement that will check whether the Check Box should be On or Off, like this:
if musicSetting == "On" {
theNameOfYourSwitch.isOn = false
} else {
theNameOfYourSwitch.isOn = true
}
In the IBAction property for your check box, add an if statement like the following that will save your Setting, depending on what it is:
if theNameOfYourCheckbox.state == NSOnState {
UserDefaults().set("On", forKey: "Music")
} else {
UserDefaults().set("Off", forKey: "Music")
}
Here's a screenshot that might help:
If you want to save the state of Switch in user default, then can use the
native method
UserDefaults.standard.set(_ value: Bool, forKey defaultName: String)
Like this
UserDefaults.standard.set(mySwitch.isOn, forKey: "SwitchStatus");
UserDefaults.standard.synchronize();
While fetching switch status just use
let status = UserDefaults.standard.bool(forKey: "SwitchStatus");
UPDATE :
#IBAction func switchpressed(_ sender: AnyObject) {
UserDefaults.standard.set(mySwitch.isOn, forKey: "SwitchStatus");
if mySwitch.isOn{
if bombSoundEffect != nil {
bombSoundEffect.stop()
bombSoundEffect = nil
}
}
else{
let path = Bundle.main.path(forResource: "newmusic.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 :(
}
}
}
Hope it helps
Happy coding ...

Having problems with saving and loading in Swift 3.0 iOS 10

I'm really new to the Swift and iOS programming scene and I am trying to learn a bunch of things. For this app, I want to save and load just one integer, but I am having problems, as everything I found on stack overflow and the Internet just doesn't seem to work on Swift 3. The app crashes immediately, it breaks on:
#IBOutlet weak var StaticLabel: UILabel!
It says "Thread 1: breakpoint 3.5" . Any help and tips would be very much appreciated :)
import UIKit
import AVFoundation
var player: AVAudioPlayer?
var number = 0
class ViewController: UIViewController {
#IBOutlet weak var StaticLabel: UILabel!
#IBOutlet weak var NumberLabel: UILabel!
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
Load()
}
func Load()
{
number = defaults.integer(forKey: "Save")
NumberLabel.text = String(number)
}
func playSound()
{
let path = Bundle.main.path(forResource: "RightYouAre.mp3", ofType: nil)
let url = URL(fileURLWithPath: path!)
do {
let sound = try AVAudioPlayer(contentsOf: url)
player = sound
sound.play()
}
catch {
// couldn't load file :(
}
}
#IBAction func Minus(_ sender: AnyObject) {
number = number - 1
NumberLabel.text = String(number)
defaults.set(number, forKey: "Save")
}
#IBAction func Plus(_ sender: UIButton) {
playSound()
number = number + 1
NumberLabel.text = String(number)
defaults.set(number, forKey: "Save")
}
}
your line of code
number = defaults.integer(forKey: "Save")
user defaults integer for key Save is nil, actually this key does not exist at all in the user defaults
before you load this integer from user defaults , it has to be set first
if defaults.object(forKey: "Save") != nil { number = defaults.integer(forKey: "Save") }
this will make sure the object exists in the user defaults before getting it's value
finally your load function should be
func Load()
{
if defaults.object(forKey: "Save") != nil
{
number = defaults.integer(forKey: "Save")
NumberLabel.text = String(number)
}
}
You need to add null handling to the load function as first time there
will be no value for the key "save" in your UserDefaults.
func Load()
{
if let number = defaults.integer(forKey: "Save")
{
self.number = number
NumberLabel.text = String(number)
}
}

Swift link Image data from Parse array using segues to secondViewController [duplicate]

This question already has answers here:
Swift link Image from Parse array using segues to secondViewController
(2 answers)
Closed 7 years ago.
Here is my code, i am trying to use the "prepareForSegue" function to send an image from tableViewController (firstViewController) to my detailedViewController (secondViewController). I have managed to populate my firstViewController from the parse cloud successfully and I have managed to get my secondViewController Labels to update, but i can not get the imageView to update. I have posted my code below
firstViewController
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let eventDetailVC: EventDetailsVC = segue.destinationViewController as! EventDetailsVC
if let selectedArrayIndex = tableView.indexPathForSelectedRow?.row {
eventDetailVC.detailNameLabel = postedEvents[selectedArrayIndex]
eventDetailVC.detailAddressLabel = postedAddress[selectedArrayIndex]
eventDetailVC.detailCityLabel = postedCity[selectedArrayIndex]
eventDetailVC.detailStateLabel = postedState[selectedArrayIndex]
eventDetailVC.detailStartLabel = postedStart[selectedArrayIndex]
eventDetailVC.detailEndLabel = postedEnd[selectedArrayIndex]
eventDetailVC.detailPriceLabel = postedPrices[selectedArrayIndex]
eventDetailVC.detailDescriptionLabel = postedDescription[selectedArrayIndex]
// The error is here....i think
postedImages[selectedArrayIndex].getDataInBackgroundWithBlock { (data, error) -> Void in
if let downloadedImage = UIImage(data: data!) {
eventDetailVC.detailImageView.image = downloadedImage
}
}
}
}
secondViewController
var detailNameLabel = String()
var detailDescriptionLabel = String()
var detailPriceLabel = String()
var detailStartLabel = String()
var detailEndLabel = String()
var detailAddressLabel = String()
var detailCityLabel = String()
var detailStateLabel = String()
var detailImageView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
detailName.text = detailNameLabel
detailDescription.text = detailDescriptionLabel
detailPrice.text = detailPriceLabel
detailStart.text = detailStartLabel
detailEnd.text = detailEndLabel
detailAddress.text = detailAddressLabel
detailCity.text = detailCityLabel
detailState.text = detailStateLabel
// its this line below....i think
detailImage.image = detailImageView.image
}
Please can someone help me figure this out, Im kinda new to this whole thing
I don't see where "detailImage" is defined, so this is assuming it is a property on .
Set a breakpoint inside the "getDataInBackgroundWithBlock" completion block to see if and when it is getting called. If it is getting called add "eventDetailVC.detailImage.image = downloadedImage" to the completion block.
Your problem is that the download of the image completes asynchronously, so by the time it has completed, your view controller has already executed the line detailImage.image = detailImageView.image with a nil image.
Rather than putting all of the code in your viewDidLoad, define didSet observers for your properties that set the appropriate UI elements. This way any time the property is updated it will automatically update the UI element;
Finally, your properties have confusing names, detailAddressLabel is actually a string and the UILabel instance seems to be named detailAddress - this has caused you to define detailImageView as UIImageView instead of a UIImage.
My suggested implementation is (after changing the names of IBOutlets and other properties to make more sense):
class someViewController : UIViewController {
#IBOutlet var detailNameLabel : UILabel! {
didSet {
self.detailNameLabel?.text=self.detailName
}
}
#IBOutlet var detailDescriptionLabel : UILabel! {
didSet {
self.detailDescriptionLabel?.text=self.detailDescription
}
}
#IBOutlet var detailPriceLabel : UILabel! {
didSet {
self.detailPriceLabel?.text=self.detailPrice
}
}
#IBOutlet var detailStartLabel : UILabel! {
didSet {
self.detailStartLabel?.text=self.detailStart
}
}
#IBOutlet var detailEndLabel : UILabel! {
didSet {
self.detailEndLabel?.text=self.detailEnd
}
}
#IBOutlet var detailAddressLabel : UILabel! {
didSet {
self.detailAddressLabel?.text=self.detailAddress
}
}
#IBOutlet var detailCityLabel : UILabel! {
didSet {
self.detailCityLabel?.text=self.detailCity
}
}
#IBOutlet var detailImageView : UIImageView! {
didSet {
self.detailImageView?.image=self.detailImage
}
}
var detailName : String = "" {
didSet {
self.detailNameLabel?.text=self.detailName
}
}
var detailDescription : String = "" {
didSet {
self.detailDescriptionLabel?.text=self.detailDescription
}
}
var detailPrice : String = "" {
didSet {
self.detailPriceLabel?.text=self.detailPrice
}
}
var detailStart : String = "" {
didSet {
self.detailStartLabel?.text=self.detailStart
}
}
var detailEnd : String = "" {
didSet {
self.detailEndLabel?.text=self.detailEnd
}
}
var detailAddress: String = "" {
didSet {
self.detailAddressLabel?.text=self.detailAddress
}
}
var detailCity : String = "" {
didSet {
self.detailCityLabel?.text=self.detailCity
}
}
var detailImage : UIImage? {
didSet {
self.detailImageView?.image=self.detailImage
}
}
}

Alamofire returns nil always in request

Usually Alamofire working nice with simple urls like:
"http://somesite.com/folder/file.json"
But when I use:
"http://somesite.com/folder/(jsonName.text).json
it always give me a nil... jsonName is a TextField as well...
That's the whole Controller:
import UIKit
import CoreLocation
import Alamofire
import SwiftyJSON
import CoreData
typealias CompletionHandler = (obj:AnyObject?, error:Bool?) -> Void
class LoginViewController: UIViewController, UITabBarControllerDelegate, UITextFieldDelegate, NSURLConnectionDelegate {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
#IBOutlet weak var wePrepareQuestLabel: UILabel!
#IBOutlet weak var downQuestProgres: UIActivityIndicatorView!
#IBOutlet weak var doNotCloseAppLabel: UILabel!
#IBOutlet weak var loginBgImage: UIImageView!
#IBOutlet weak var EmptyCodeError: UILabel!
#IBOutlet weak var loginTabBarItem: UITabBarItem!
#IBOutlet weak var QuestCodeTextField: UITextField!
#IBOutlet weak var loginTextFieldImage: UIImageView!
#IBOutlet weak var downloaded: UIButton!
#IBOutlet weak var createQuestButton: UIButton!
#IBAction func createQuest(sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("WebViewController") as! UIViewController
self.presentViewController(vc, animated: true, completion: nil)
}
let Path: String = ""
#IBAction func QuestFetchButton(button: UIButton) {
if QuestCodeTextField.text.isEmpty {
EmptyCodeError.hidden = false
}
else if IJReachability.isConnectedToNetwork() {
}
else
{
QuestCodeTextField.hidden = true
button.hidden = true
EmptyCodeError.hidden = true
createQuestButton.hidden = true
doNotCloseAppLabel.hidden = false
wePrepareQuestLabel.hidden = false
loginTextFieldImage.hidden = true
downQuestProgres.hidden = false
self.downloaded.hidden = false
// questDownloadSaveJSON()
var objThisVC = LoginViewController()
objThisVC.callAndGetResponse { (obj, error) -> Void in
if (obj != nil) {
self.setUpDataInCoreData(obj)
print("ALL DIE")
self.performSegueWithIdentifier("QuestsListViewController", sender: nil)
}
else {
println("Response nil!!")
}
}
}
}
var file:NSFileHandle?
var pathURL: NSURL
{
let folder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let path = folder.stringByAppendingPathComponent("\(QuestCodeTextField.text).json")
let url = NSURL(fileURLWithPath: path)
return url!
}
var code: String = ""
override func viewDidLoad() {
super.viewDidLoad()
QuestCodeTextField.text = code
self.QuestCodeTextField.delegate = self;
}
func setUpDataInCoreData(obj:AnyObject?){
println("Web Serviece Response \(obj)")
let dirEvent = obj as! NSDictionary
var aryEvent = dirEvent.valueForKey("events") as! NSArray
var indexEvent : Int = 0;
for (dirContent) in aryEvent
{
// Create Event Instance
var newItem: Events = NSEntityDescription.insertNewObjectForEntityForName("Events", inManagedObjectContext: self.appDelegate.cdh.backgroundContext!) as! Events
newItem.title = dirContent.valueForKey("title") as! String
newItem.indexID = String(indexEvent++) as String
println(newItem.title)
println(newItem.indexID)
var indexContent : Int = 0;
var aryContent = dirContent.valueForKey("content") as! NSArray
for (dirContentDetail) in aryContent{
var contentEntity: Content = NSEntityDescription.insertNewObjectForEntityForName("Content", inManagedObjectContext: self.appDelegate.cdh.backgroundContext!) as! Content
contentEntity.content_type = dirContentDetail.valueForKey("content_type") as! String
contentEntity.visible = dirContentDetail.valueForKey("visible") as! Bool
contentEntity.indexID = String(indexContent++) as String
println(contentEntity.content_type)
println(contentEntity.visible)
if contentEntity.content_type == "text"{
contentEntity.data_type = dirContentDetail.valueForKey("data") as! String
}
else if contentEntity.content_type == "image" || contentEntity.content_type == "audio" || contentEntity.content_type == "video" || contentEntity.content_type == "choice" {
contentEntity.data_type = ""
if (dirContentDetail.valueForKey("data") != nil && dirContentDetail.valueForKey("data")?.count>0 )
{
var indexImage : Int = 0;
var aryDTImages = dirContentDetail.valueForKey("data") as! NSArray
if aryDTImages.count > 0 {
for strContentDetail in aryDTImages as! [String]{
var objDtImg : DataTypeImage = NSEntityDescription.insertNewObjectForEntityForName("DataTypeImage", inManagedObjectContext: self.appDelegate.cdh.backgroundContext!) as! DataTypeImage
var strURL : NSString = NSString(string: strContentDetail)
objDtImg.urlString = strURL as String
objDtImg.indexID = String(indexImage++) as String
objDtImg.dtImages = contentEntity
// her have to set image to content
contentEntity.content = newItem
}
}
}
}
// here have to set entity to content
contentEntity.content=newItem
}// this is the end of content for loop
}// end of aryEvent
// here to save statement
self.appDelegate.cdh.saveContext(self.appDelegate.cdh.backgroundContext!)
// self.table.reloadData()
}
func callAndGetResponse(complitionHandler : CompletionHandler){
complitionHandler(obj: nil, error: true)
Alamofire.request(.GET, "http://g57732cr.bget.ru/\(QuestCodeTextField.text).json").responseJSON() {
(_, _, data, error) in
if error == nil {
complitionHandler(obj: data, error: false)
}
else{
complitionHandler(obj: nil, error: true)
self.performSegueWithIdentifier("QuestsListViewController", sender: nil)
}
// Fetch all data from Core Data
//self.fetchAllData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Hide keyboard by tap on the rest of the view
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
view.endEditing(true)
}
//ReturnButton hides keyboard
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "QuestsListViewController"){
var destination = segue.destinationViewController as! UINavigationController
let VC = destination.topViewController as! QuestListViewController
VC.questCode = self.QuestCodeTextField.text
}
}
}

Resources