App crash when reload button is pressed - ios

i'm having some problems with my weather app for iOS.
I'm new in programming in xCode, so it could be a silly error.
Anyway, the problem is: I'm trying to add a refresh button in my Single Page App. The button has a IBAction function associated, so that when it is pressed it should get hidden and the activity indicator should appear.
That is the function:
#IBAction func reload() {
refreshButton.hidden = true
refreshActivityIndicator.hidden = false
refreshActivityIndicator.startAnimating()
}
and that is the declaration of the variables:
#IBOutlet weak var refreshButton: UIButton!
#IBOutlet weak var refreshActivityIndicator: UIActivityIndicatorView!
when i run the app and press the refresh button, the app crash and i get this error:
#UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { <--thread 1 signal sigarbt
the console doesn't show anything else.
What could be the problem?
// APPDELEGATE.SWIFT
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
application.setStatusBarHidden(true, withAnimation: .None)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
//VIEWCONTROLLER.SWIFT
import UIKit
import Foundation
class ViewController: UIViewController {
private let apiKey = "447073dc853014a6fa37376c43d8462b"
#IBOutlet weak var iconView: UIImageView!
#IBOutlet weak var currentTimeLabel: UILabel!
#IBOutlet weak var temperatureLabel: UILabel!
#IBOutlet weak var humidityLabel: UILabel!
#IBOutlet weak var precipitationLabel: UILabel!
#IBOutlet weak var summaryLabel: UILabel!
#IBOutlet weak var refreshButton: UIButton!
#IBOutlet weak var refreshActivityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
refreshActivityIndicator.hidden = true
// base URL
let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/")
// add coordinates to base url (API syntax)
let forecastURL = NSURL(string: "44.698150,10.656846", relativeToURL: baseURL)
// NSURL SESSION
//The NSURLSession class and related classes provide an API for downloading content via HTTP. This API provides a rich set of delegate methods for supporting authentication and gives your app the ability to perform background downloads when your app is not running or, in iOS, while your app is suspended. With the NSURLSession API, your app creates a series of sessions, each of which coordinates a group of related data transfer tasks. For example, if you are writing a web browser, your app might create one session per tab or window. Within each session, your app adds a series of tasks, each of which represents a request for a specific URL (and for any follow-on URLs if the original URL returned an HTTP redirect).
let sharedSession = NSURLSession.sharedSession()
let downloadTask : NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler:
{ (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
if (error == nil) {
let dataObject = NSData(contentsOfURL: location) // convert in NSData object
// serialize NSData object in Json as Dictionary
let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary
// instance of Current (Current.swift) init with weatherDictionary
let currentWeather = Current(weatherDictionary: weatherDictionary)
// we put the code in the main queue cause this is relative the UI, that have the first thread (concurrency)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.temperatureLabel.text = "\(currentWeather.temperature)"
self.iconView.image = currentWeather.icon!
self.currentTimeLabel.text = "At \(currentWeather.currentTime!) it is"
self.humidityLabel.text = "\(currentWeather.humidity)"
self.precipitationLabel.text = "\(currentWeather.precipProbability)"
self.summaryLabel.text = "\(currentWeather.summary)"
// Stop refresh animation
self.refreshActivityIndicator.stopAnimating()
self.refreshActivityIndicator.hidden = true
self.refreshButton.hidden = false
})
}
})
downloadTask.resume() // call sharedSession.downloadTaskWithURL -> store json data in location (local temporary memory)
}
#IBAction func reload() {
println("PRESSED")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I haven't got any .h or .m file.

Is reload function even getting called? If you are using storyboard/Xib for creating the UIButton then link the reload function in Xib on touchUpInside Event or if you are creating the UIButton event in code then like below:
Create another UIButton property in .h file:
#property(nonatomic, strong) UIButton *refresh;
In .m file
-(void) viewDidLoad {
self.refresh = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.refresh addTarget:self
action:#selector(reload:) forControlEvents:UIControlEventTouchUpInside];
[self.refresh setTitle:#"Reload" forState:UIControlStateNormal];
self.refresh .frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.view addSubview:self.refresh];
}
-(void) reload:(UIButton*)sender
{
NSLog(#"you clicked on button %#", sender.tag);
if(self.refresh.hidden) {
self.refresh.hidden = false;
} else {
self.refresh.hidden = true;
}
}

Okay it works!
Please don't ask me why :)
I simply deleted the code and rewrote it. And it works. Call it magic.
Thank you all for your answers.

Related

I want to use "applicationWillEnterForeground", however my function requires an UIImageView and I can't call on it in AppDelegate?

I have an image on a website, and I want it to be put into a UIImageView, however I want it to refresh every time the application is launched.
I have the following code in a ViewController:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var image: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
get_image("WEBSITE.com/image.jpg", image)
}
func get_image(_ url_str:String, _ imageView:UIImageView)
{
let url:URL = URL(string: url_str)!
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: {
(
data, response, error) in
if data != nil
{
let image = UIImage(data: data!)
if(image != nil)
{
DispatchQueue.main.async(execute: {
imageView.image = image
imageView.alpha = 0
UIView.animate(withDuration: 2.5, animations: {
imageView.alpha = 1.0
})
})
}
}
})
task.resume()
}
}
Since the image in WEBSITE.com/image.jpg is going to change often, I wan't the app to pull the image everytime it launches. I did some research, and was told to put the following code into my AppDelegate.
func applicationWillEnterForeground(_ application: UIApplication) {
ViewController().get_image("WEBSITE.com/image.jpg", image)
}
However, after the link, the "image" doesn't work. How do I reference the image in the AppDelegate file?
BTW, I get the following error message:
"Cannot convert value of type 'module' to expected argument type 'UIImageView'"
What do I do?
You can use the observer pattern to let ViewController know when the app will enter the foreground.
UIScene has a built in notification that you can simply observe from within the viewDidLoad of your view controller.
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(get_image), name: UIScene.willEnterForegroundNotification, object: nil)
}
The selector is the action taken whenever your view controller observes willEnterForegroundNotification. In order to use get_image as a selector you will also need to expose it to the Objective-C runtime by writing #Objc before the func keyword.

Swift 4 error: [<UIViewController 0x7ff66ec0ef30> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key emailField

I've tried to link a couple objects in a xib file to my code for the View Controller through IBOutlets, but when I run the code I get the error
'NSUnknownKeyException', reason: '[< UIViewController 0x7f94dfc0f110>
setValue:forUndefinedKey:]: this class is not key value
coding-compliant for the key emailField.'
I've tried deleting all the outlets and reassigning them, and checking that all the connected objects only have one respective outlet each. Also, when unlinking one element, its error goes away, but the same format of the error for a different linked element appears.
import UIKit
import FirebaseAuth
import Firebase
class SignUpViewController: UIViewController {
#IBOutlet weak var nameField: UITextField!
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func toSignUp(_ sender: Any) {
Auth.auth().createUser(withEmail: emailField.text!, password: passField.text!, completion: nil)
Firestore.firestore().collection("users").document(usernameField.text!).setData([
"name" : nameField.text!,
"username" : usernameField.text!,
"email" : emailField.text!
])
TransitionModel().transitionModel(viewControllerName: "LoginViewController", newView: LoginViewController().view!, viewControllerCurrent: self)
}
#IBAction func toLogin(_ sender: Any) {
TransitionModel().transitionModel(viewControllerName: "LoginViewController", newView: LoginViewController().view!, viewControllerCurrent: self)
}
}
import UIKit
import Firebase
class LoginViewController: UIViewController {
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func toLogin(_ sender: Any) {
}
}
import UIKit
import CoreData
import Firebase
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = UIViewController(nibName: "SignUpViewController", bundle: nil)
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Pono_Beta")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
Thank you in advance for responses.
This happens when you just copy paste view controller.
Goto Storyboard, Select View Controller Open connection inspector and remove connections for emailField and create new Outlet

IBAction causes EXC_BAD_ACCESS in AppDelegate

I am writing a project for iOS in swift using the DJI Mobile SDK and the UXSDK sample application (found here: https://github.com/dji-sdk/Mobile-UXSDK-iOS).
I added a ViewController with an IBAction getData(_ sender:) which sends a message successfully to a DJI product. When the IBAction completes, the app crashes with a EXC_BAD_ACCESS error in AppDelegate.swift
Error flag in AppDelegate
import UIKit
import Foundation
//To use DJI Bridge app, change `useBridge` to true and add bridge app
IP address in `debugID`
let useBridge = false
let debugIP = "BRIDGE_APP_IP_ADDRESS_HERE"
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,
UISplitViewControllerDelegate {
var window: UIWindow?
open var productCommunicationManager = ProductCommunicationManager()
open var communicationsViewController = CommunicationsViewController()
open var osdkDevice:OnboardSDKDevice?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Start the registration at the launch of the app. This can be retriggered at anytime from the main view.
// DJI App key needs to be registered in the Info.plist before calling this method.
self.productCommunicationManager.registerWithProduct()
return true
}
}
Here is the view controller. It isn't the main one, but it is navigated to through the main view controller.
import UIKit
import Foundation
import DJISDK
import DJIUXSDK
class CommunicationsViewController: UIViewController, UITextViewDelegate {
//This is instantiated as a UIViewController as soon as app launches
//The reference in appDelegate is reassigned every time the view launches
//MARK: Properties
#IBOutlet weak var DataDisplay: UITextView!
open weak var appDelegate = UIApplication.shared.delegate as? AppDelegate
//MARK: Methods
override func viewDidLoad() {
super.viewDidLoad()
appDelegate?.communicationsViewController = self
appDelegate?.productCommunicationManager.connectToProduct()
appDelegate?.productCommunicationManager.connectedProduct = DJISDKManager.product()
if (appDelegate?.productCommunicationManager.connectedProduct?.model != nil){
self.DataDisplay.text = (appDelegate?.productCommunicationManager.connectedProduct.model)
}
appDelegate?.osdkDevice = OnboardSDKDevice()
appDelegate?.osdkDevice?.delegate = appDelegate?.osdkDevice
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: Actions
#IBAction func back(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
#IBAction func getData(_ sender: UIButton) {
//Create 4 bytes of 0's
let data = Data(count: 4)
appDelegate?.osdkDevice?.sendDataFromMobile(toOnboard: data, withCompletion: nil)
//App crashes after exiting scope
}
}
I have found that EXC_BAD_ACCESS is caused by trying to access memory that is no longer available. I have double checked the connections of all my IBActions and IBOutlets and they seem to be okay.
This is the error message from "bt" in the console
Console and assembly from exception breakpoint
Could somebody help me diagnose the crash?
iOS programming and Swift are both pretty new to me, so if there anything missing in this description please let me know. Thanks

swift3 how to Change screen when app changes to background status

in swift3
I want to change the screen to hide the original screen when the app is in the background state.
For example, if you press the home button twice while the app is running, the screen will change to a different screen.
I want to set the screen to change to LaunchScreen.
Thank you for your help.
Try this one:
func applicationDidEnterBackground(_ application: UIApplication) {
let imageView = UIImageView(frame: self.window!.bounds)
imageView.tag = 1001
imageView.image = UIImage(named: "") //your image goes here
UIApplication.shared.keyWindow?.subviews.last?.addSubview(imageView)
}
func applicationWillEnterForeground(_ application: UIApplication) {
if let imageView : UIImageView = UIApplication.shared.keyWindow?.subviews.last?.viewWithTag(1001) as? UIImageView {
imageView.removeFromSuperview()
}
}
"If you do not want your application to remain in the background when it is quit, you can explicitly opt out of the background execution model by adding the UIApplicationExitsOnSuspend key to your application’s Info.plist file and setting its value to YES.
When an application opts out, it cycles between the not running, inactive, and active states and never enters the background or suspended states.
When the user taps the Home button to quit the application, the applicationWillTerminate: method of the application delegate is called and the application has approximately five seconds to clean up and exit before it is terminated and moved back to the not running state."
s
Add this function in your AppDelegate.
func applicationWillResignActive(_ application: UIApplication) {
// Change the view to show what you want here.
}
This method is called to let your app know that it is about to move
from the active to inactive state. This can occur for certain types of
temporary interruptions (such as an incoming phone call or SMS
message) or when the user quits the app and it begins the transition
to the background state.
Source: https://developer.apple.com/reference/uikit/uiapplicationdelegate/1622950-applicationwillresignactive
This is common scenario where we want to avoid screen-shotting by iOS while going to BG or covering app screens when app is in stack.
Here is what I'm doing:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private var appCoverWindow: UIWindow?
private var appCoverVC: UIViewController?
func applicationDidBecomeActive(_ application: UIApplication) {
if appCoverWindow != nil {
appCoverWindow!.isHidden = true
appCoverWindow!.rootViewController = nil
appCoverWindow = nil
appCoverVC = nil
}
}
func applicationWillResignActive(_ application: UIApplication) {
appCoverVC = rootViewController().storyboard!.instantiateViewController(withIdentifier: "AppCoverVCId") as! AppCoverViewController
appCoverWindow = UIWindow(frame: UIScreen.main.bounds)
let existingTopWindow = UIApplication.shared.windows.last
appCoverWindow!.windowLevel = existingTopWindow!.windowLevel + 1
appCoverVC!.view.frame = appCoverWindow!.bounds
appCoverWindow!.rootViewController = appCoverVC!
appCoverWindow!.makeKeyAndVisible()
}
class func appLaunchImage() -> UIImage? {
//this method will return LaunchImage
let launchImageNames = Bundle.main.paths(forResourcesOfType: "png", inDirectory: nil).filter { (imageName) -> Bool in
return imageName.contains("LaunchImage")
}
for imageName in launchImageNames {
guard let image = UIImage(named: imageName) else { continue }
// if the image has the same scale and dimensions as the current device's screen...
if (image.scale == UIScreen.main.scale) && (image.size.equalTo(UIScreen.main.bounds.size)) {
return image
}
}
return nil
}
}
Instead of using UIWindow to cover app, we can directly use UIViewController also, but that may cause issues if keyboard is present while going to BG.
Here is AppCoverViewController.swift:
(It has XIB in storyboard with one full screen UIImageView)
class AppCoverViewController: BaseViewController {
#IBOutlet weak var bgImageView: UIImageView!//full screen image view
override func viewDidLoad() {
super.viewDidLoad()
if let image = AppDelegate.appLaunchImage() {
bgImageView.image = image
}
}
override func deviceOrientationDidChange() {
if let image = AppDelegate.appLaunchImage() {
bgImageView.image = image
}
}
}
This class takes care of device rotations also.

iOS Simulator Stuck on Launch Page after Update to XCode 7

I updated to Xcode 7 from Xcode 6 and updated my code to swift 2.0 from swift 1.2. When I run the project, there are no compile time errors, just warnings, and the build is successful. The problem I am having is that the main.storyboard does not load. By this i mean all that is shown in the simulator is the launch page and the initial view controller is never put into the hierarchy (i believe). When i updated my code to swift 2.0, i manually updated the AppDelegate which i did not expect and is why i think there may be something wrong with the file. I also get a Thread 1: EXC_BAD_ACCESS (code=2 ...) error which i understand to be a recursion error but don't understand how to resolve the issue.
Things I have tried
Reinstalling Xcode 7
Using Simulator 8.4 instead of 9.0
Updated to last swift syntax (Edit->Convert->To Latest Swift Syntax)
Here is my AppDelegate File
import UIKit
import CoreData
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.wt9t.BaseballsInsightVersionBeta" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("BaseballsInsightVersionBeta", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("BaseballsInsightVersionBeta.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
let mOptions = [NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true]
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch let error as NSError {
print(error.localizedDescription)
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext!.hasChanges {
do {
try managedObjectContext!.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
Also i am including my initial view controller called MainVC
import UIKit
import CoreData
import Foundation
import SystemConfiguration
class MainVC: UIViewController {
#IBOutlet var chartCountTextView: UITextView!
let cdao = CoreDataRequests()
var chartsCompleted:Array<String> = []
override func viewDidLoad() {
super.viewDidLoad()
print("Viewdidload finished")
self.view.backgroundColor = UIColor.darkGrayColor()
let count = cdao.getChartCountInQueue()
if(count != 0)
{
chartCountTextView.text = "\(count) charts have yet to be uploaded, click Chart Queue to start the process"
}
else
{
chartCountTextView.text = ""
}
chartCountTextView.backgroundColor = UIColor.clearColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
let email = NSUserDefaults.standardUserDefaults().stringForKey("userEmail")
let password = NSUserDefaults.standardUserDefaults().stringForKey("userPassword")
if(email == nil || password == nil)
{
self.performSegueWithIdentifier("login", sender: self)
}
}
}

Resources