Realm. Update data within multiple ViewControllers - ios

I'm trying to create an App, that takes a initial condition and save it in Realm database.
Here is the code for my Realm class:
class FunctionData: Object {
#objc dynamic var Name = ""
#objc dynamic var status = false
#objc dynamic var statusComment = ""
#objc dynamic var tester = ""
override static func primaryKey() -> String? {
return "functionNames"
}
}
I created a TableViewController with the "Name" as the name for each Cell. I want to click on the cell and go to the "SecondViewController" and there, fill the other Information, like tester and Comment.
The TableViewController works well.
here the code, to make the segue to the SecondViewController:
var functions: Results<FunctionData>?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let function = functions![indexPath.row]
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let functionsVC = storyboard.instantiateViewController(identifier: "functionsVC") as! FunctionsRatingViewController
functionsVC.name = function.functionNames
functionsVC.functionID = function.functionNames
if let indexPath = tableView.indexPathForSelectedRow {
functionsVC.selectedFunction = functions![indexPath.row]
}
self.present(functionsVC, animated: true, completion: nil)
}
But in my SecondVC I am not able to save the other Information in the selected "Item". I'm trying to do that with a AlertController
var selectedFunction: FunctionData? {
didSet {
}
}
func showAlert() {
var textField = UITextField()
let alert = UIAlertController(title: "Status not OK", message: nil, preferredStyle: .alert)
alert.addTextField {
$0.placeholder = "Comment"
$0.addTarget(alert, action: #selector(alert.textDidChangeInLoginAlert), for: .editingChanged)
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
let loginAction = UIAlertAction(title: "Save", style: .default) { [unowned self] _ in
if let currentFct = self.selectedFunction {
do {
try self.realm.write {
currentFct.realm?.create(FunctionData.self, value: ["statusComment": textField.text], update: .modified)
}
} catch {
print("Error trying to append a Comment, \(error)")
}
}
print("Comment saved")
}
loginAction.isEnabled = false
alert.addAction(loginAction)
present(alert, animated: true)
}
Thanks a lot for any help!

The primary key on your Realm object is showing to be return "functionNames"
class FunctionData: Object {
#objc dynamic var Name = ""
#objc dynamic var status = false
#objc dynamic var statusComment = ""
#objc dynamic var tester = ""
override static func primaryKey() -> String? {
return "functionNames"
}
}
but you've not included that property in the object, so it won't work.
Update your object to include that property
class FunctionData: Object {
#objc dynamic var functionName = UUID().uuidString //for example
#objc dynamic var Name = ""
#objc dynamic var status = false
#objc dynamic var statusComment = ""
#objc dynamic var tester = ""
override static func primaryKey() -> String? {
return "functionNames"
}
}
Also, primary keys are unique and singular so calling it functionNames is probably not the best move. Try functionName or even, and more appropriately function_id.
There may be additional issues but that's the first that should be addressed.

Related

Why am I getting a Unexpectedly found nil while implicitly unwrapping an Optional value in my Code?

I am getting a Unexpectedly found nil while implicitly unwrapping an Optional value in my Code error when I try to use another view controller to save a new task in a to do list. When I tap a button I open up the entry page which then has a text field where I can enter the text to then create a task item. Here is the code for the main view controller:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
#IBOutlet var tableView: UITableView!
private var tasks = [TaskItem]()
override func viewDidLoad() {
super.viewDidLoad()
getAllTasks()
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = tasks[indexPath.row].title
return cell
}
#IBAction func didTapNewTask(){
let viewContoller = storyboard?.instantiateViewController(identifier: "entry") as! EntryViewController
viewContoller.title = "New Task"
viewContoller.update = {
DispatchQueue.main.async {
self.getAllTasks()
}
}
navigationController?.pushViewController(viewContoller, animated: true)
}
//Core Data Functions
//Used to get all our tasks in our Core Data
func getAllTasks() {
do {
tasks = try context.fetch(TaskItem.fetchRequest())
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch {
print("error getting all tasks \(error)")
}
}
//This is used to create a task, setting the properties to those in the parameters and then saving to our Core Data.
func createTask(title: String, notes: String, difficulty: Int32) {
let task = TaskItem(context: context)
task.title = title
task.notes = notes
task.difficulty = difficulty
task.dateCreated = Date()
do {
try context.save()
getAllTasks()
}
catch {
}
}
Here is the code for the entry view controller:
class EntryViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var field: UITextField!
var update: (() -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
field.delegate = self
// Do any additional setup after loading the view.
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
saveTask()
return true
}
#IBAction func saveTask(){
let vc = storyboard?.instantiateViewController(identifier: "tasks") as! ViewController
guard let text = field.text, !text.isEmpty else {
let alert = UIAlertController(title: "Error", message: "Please input a title" , preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Confirm", style: UIAlertAction.Style.default, handler: nil))
self.present(alert,animated: true,completion: nil)
return
}
vc.createTask(title: text, notes: "Hello", difficulty: 10)
update?()
navigationController?.popViewController(animated: true)
}
The app crashes once I click save the new task but then once I reload the app the task I just created is there.
#IBAction func saveTask(){
let vc = storyboard?.instantiateViewController(identifier: "tasks") as! ViewController
guard let text = field.text, !text.isEmpty else {
let alert = UIAlertController(title: "Error", message: "Please input a title" , preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Confirm", style: UIAlertAction.Style.default, handler: nil))
self.present(alert,animated: true,completion: nil)
return
}
vc.createTask(title: text, notes: "Hello", difficulty: 10)
update?()
navigationController?.popViewController(animated: true)
}
The first line of this method is the source of your problem. What you're doing here is making a new instance of the original view controller, not the instance you first came from.
This sort of works for a moment, because you then call createTask on that view controller to make your new task. That's fine, but that method then calls getAllTasks, which then dispatches to the main queue, which then calls reload data on your table.
But your table doesn't exist, because this is a new instance of the view controller which has never had it's view loaded. The table view is an implicitly unwrapped optional, but it's nil when you hit it here.
Your best solution is to pass in a block (like you have with update) to create a new task, and in that block call methods on the original view controller.

Get selected text from custom UIMenuItem in WKWebView

I am creating an iOS app that has a custom UIMenuItem. This new custom UIMenuItem shows up when text is selected in WKWebView. How do I get the selected text.
I followed instructions in https://stackoverflow.com/a/49761522/6828076 to create a custom UIMenuItem. It works fine, but I need the selected text that was used when the custom UIMenuItem was tapped. There are many posts about using UIPasteboard but the custom item does not copy the selected text into the UIPasteboard, so I am unable to retrieve it.
func setupCustomMenu() {
let customMenuItem = UIMenuItem(title: "Foo", action:
#selector(ViewController.transelateMenuTapped))
UIMenuController.shared.menuItems = [customMenuItem]
UIMenuController.shared.update()
}
#objc func transelateMenuTapped() {
let yay = //Need to retrieve the selected text here
let alertView = UIAlertController(title: "Yay!!", message: yay, preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: "cool", style: .default, handler: nil))
present(alertView, animated: true, completion: nil)
}
You can use Javascript for that.
Here's the code from the the answer you used, slightly altered to get the selected text by evaluating Javascript on the WKWebView:
import UIKit
import WebKit
class ViewController: UIViewController {
weak var webView: CustomMenuWebView!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
prepareWebView()
}
#objc func translateMenuTapped(_ test: Any) {
webView.evaluateJavaScript("window.getSelection().toString()") { (test, error) in
guard let test = test as? String, error == nil else { return }
// ***** Here's the user's selected text *****
print(test)
}
}
}
private extension ViewController {
func prepareWebView() {
addWebViewToView()
loadWebViewContent()
setupCustomMenu()
}
func addWebViewToView() {
let webView = CustomMenuWebView(
frame: view.bounds, configuration: WKWebViewConfiguration())
view.addSubview(webView)
self.webView = webView
}
func loadWebViewContent() {
let url = URL(string: "https://www.google.com")
let request = URLRequest(url: url!)
webView.load(request)
}
func setupCustomMenu() {
let customMenuItem = UIMenuItem(
title: "Translate", action: #selector(ViewController.translateMenuTapped))
UIMenuController.shared.menuItems = [ customMenuItem ]
UIMenuController.shared.update()
}
}
class CustomMenuWebView: WKWebView {
// Turn off all other menu items
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return false
}
}

iOS Swift fetching more data for collection view after having navigated to detail view not working

I am working on an assignment for a job interview. I have finished most of the assignment. There's only a bug i can't figure out. I have been trying for three days now.
I had to make a client app for the Flickr API that allows users to search for photos using specific words. Display the results in a collection view with infinite scroll. And when a photo is selected it should show the details of the photo in a detail view.
The bug:
Everything is working if i stay in the collection view. I can search over and over again and the infinite scroll is also working.As soon as a specific index in the index path is hit. A new request is sent with the same search term. But if i select a photo and then navigate back to the collection view and try a new search nothing comes back and my error handeling returns an error. (the error is not a console error).Also when navigating back from detail to collection. I can still scroll until the index triggers a new request than it also throws an error.
I hope i am explaining it well. I am really getting desperate at the moment. I tried everything i could think of: the request url still works when i try it in the browser.
Please help! If you need more info just ask.
Collection view controller:
import UIKit
// Global variable for holding a search term.
var searchTerm: String?
// Global variable to hold an instance of Reachability.
var reachability: Reachability?
// Enum for changing the textfield placeholder text.
enum TextFieldPlaceHolderText: String {
case Search = "Search"
case Searching = "Searching..."
}
class PhotosViewController: UIViewController {
// MARK: - Outlets
#IBOutlet var collectionView: UICollectionView!
#IBOutlet var searchTextField: UITextField!
// MARK: - Properties
let photoDataSource = PhotoDataSource()
let photoStore = PhotoStore()
// MARK: - View Setup
override func viewDidLoad() {
super.viewDidLoad()
// Sets the data source and delegate.
collectionView.dataSource = photoDataSource
collectionView.delegate = self
// Uses an image to add a pattern to the collection view background.
collectionView.backgroundColor = UIColor(patternImage: UIImage(named: "flickr.png")!)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Checks if the device is connected to the internet.
checkForReachability()
}
// MARK: showAlert
func showAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "Ok", style: .Cancel, handler: { (nil) in
self.dismissViewControllerAnimated(true, completion: nil)
})
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
}
// MARK: - Segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowPhoto" {
if let selectedIndexPath = collectionView.indexPathsForSelectedItems()?.first {
let flickrPhoto = photoDataSource.flickrPhotos[selectedIndexPath.row]
let destinationVC = segue.destinationViewController as! PhotoDetailViewController
destinationVC.flickrPhoto = flickrPhoto
destinationVC.photoStore = photoStore
}
}
}
// MARK: - checkForReachability
func checkForReachability() {
do {
reachability = try Reachability.reachabilityForInternetConnection()
} catch {
print("Unable to create Reachability")
return
}
reachability!.whenReachable = { reachability in
// This is called on a background thread, but UI updates must be on the main thread.
NSOperationQueue.mainQueue().addOperationWithBlock({
if reachability.isReachableViaWiFi() {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
})
}
reachability!.whenUnreachable = { reachability in
// This is called on a background thread, but UI updates must be on the main thread.
NSOperationQueue.mainQueue().addOperationWithBlock({
print("Not reachable")
self.showAlert("No Internet Connection", message: "Make sure your device is connected to the internet.")
})
}
do {
try reachability!.startNotifier()
} catch {
print("Unable to start notifier")
}
}
}
//MARK: - Extension UICollectionViewDelegate
extension PhotosViewController: UICollectionViewDelegate {
//MARK: - willDisplayCell
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
let flickrPhoto = photoDataSource.flickrPhotos[indexPath.row]
// Downloads the image data for a thumbnail.
photoStore.fetchImageForPhoto(flickrPhoto,thumbnail: true) { (result) -> Void in
// Calls the mainthread to update the UI.
NSOperationQueue.mainQueue().addOperationWithBlock() {
// The indexpath for the photo might have changed between the time the request started and finished, so find the most recent indeaxpath
let photoIndex = self.photoDataSource.flickrPhotos.indexOf(flickrPhoto)!
let photoIndexPath = NSIndexPath(forRow: photoIndex, inSection: 0)
// When the request finishes, only update the cell if it's still visible
if let cell = collectionView.cellForItemAtIndexPath(photoIndexPath) as? PhotoCollectionViewCell {
cell.updateWithImage(flickrPhoto.image)
}
}
}
}
}
//MARK: - Extension UITextFieldDelegate
extension PhotosViewController : UITextFieldDelegate {
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Checks if the textfield is not empty.
if textField.text!.isEmpty {
self.showAlert("S😉rry", message: "No search term detected, please enter a search term.")
return false
}
else {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
textField.addSubview(activityIndicator)
activityIndicator.frame = textField.bounds
activityIndicator.startAnimating()
textField.placeholder = TextFieldPlaceHolderText.Searching.rawValue
// Sets the text that the user typed as the value for the searchTerm property.
searchTerm = textField.text!
// Fetches the photos from flickr using the user's search term.
photoStore.fetchPhotosForSearchTerm() {
(photosResult) -> Void in
// Calls the mainthread to update the UI.
NSOperationQueue.mainQueue().addOperationWithBlock() {
switch photosResult {
case let .Success(photos):
// Checks if photos were found using the search term.
if photos.count == 0 {
self.showAlert("S😞rry", message: "No images found matching your search for: \(searchTerm!), please try again.")
}
activityIndicator.removeFromSuperview()
textField.placeholder = TextFieldPlaceHolderText.Search.rawValue
// Sets the result to the data source array.
self.photoDataSource.flickrPhotos = photos
print("Successfully found \(photos.count) recent photos.")
case let .Failure(error):
self.checkForReachability()
activityIndicator.removeFromSuperview()
textField.placeholder = TextFieldPlaceHolderText.Search.rawValue
self.photoDataSource.flickrPhotos.removeAll()
self.showAlert("", message: "Something went wrong, please try again.")
print("Error fetching photo's for search term: \(searchTerm!), error: \(error)")
}
self.collectionView.reloadSections(NSIndexSet(index: 0))
}
}
textField.text = nil
textField.resignFirstResponder()
self.collectionView?.backgroundColor = UIColor.whiteColor()
return true
}
}
}
The detail view controller:
import UIKit
import Social
class PhotoDetailViewController: UIViewController {
// MARK: - Outlets
#IBOutlet var photoTitleLabel: UILabel!
#IBOutlet var photoIDLabel: UILabel!
#IBOutlet var dateTakenLabel: UILabel!
#IBOutlet var imageView: UIImageView!
// MARK: Properties
var flickrPhoto: FlickrPhoto!
var photoStore: PhotoStore!
let formatter = FlickrAPI.dateFormatter
// MARK: - View Setup
override func viewDidLoad() {
super.viewDidLoad()
//Downloads the image data for large image
photoStore.fetchImageForPhoto(flickrPhoto, thumbnail: false) { (result) -> Void in
switch result {
case let .Success(image):
// Calls the mainthread to update the UI.
NSOperationQueue.mainQueue().addOperationWithBlock() {
self.imageView.image = image
}
case let .Failure(error):
print(" Error fetching detail image for photo: \(error)")
}
}
// Formats the date a shorte date that doesn't display the time
formatter.dateStyle = .MediumStyle
formatter.timeStyle = .NoStyle
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Checks if the device is connected to the internet.
checkForReachability()
// Configures the UI.
configureView()
}
// MARK: - checkForReachability
func checkForReachability() {
do {
reachability = try Reachability.reachabilityForInternetConnection()
} catch {
print("Unable to create Reachability")
return
}
reachability!.whenReachable = { reachability in
// this is called on a background thread, but UI updates must be on the main thread, like this:
NSOperationQueue.mainQueue().addOperationWithBlock({
if reachability.isReachableViaWiFi() {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
})
}
reachability!.whenUnreachable = { reachability in
// this is called on a background thread, but UI updates must be on the main thread, like this:
NSOperationQueue.mainQueue().addOperationWithBlock({
print("Not reachable")
self.showAlert("No Internet Connection", message: "Make sure your device is connected to the internet.")
})
}
do {
try reachability!.startNotifier()
} catch {
print("Unable to start notifier")
}
}
// MARK: - configureView
func configureView() {
photoTitleLabel.text = flickrPhoto.title ?? "No title available"
photoIDLabel.text = flickrPhoto.photoID ?? "ID unknown"
dateTakenLabel.text = formatter.stringFromDate(flickrPhoto.dateTaken) ?? " Date unknown"
}
// MARK: - showShareOptions
#IBAction func showShareOptions(sender: AnyObject) {
// Configure an action sheet to show the sharing options.
let actionSheet = UIAlertController(title: "Share this photo", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
let tweetAction = UIAlertAction(title: "Share on Twitter", style: UIAlertActionStyle.Default) { (action) -> Void in
// Check if sharing to Twitter is possible.
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) {
let twitterComposeVC = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
twitterComposeVC.addImage(self.imageView.image)
self.presentViewController(twitterComposeVC, animated: true, completion: nil)
}
else {
self.showAlert("Flickr Searcher", message: "You are not logged in to your Twitter account.")
}
}
// Configure a new action to share on Facebook.
let facebookPostAction = UIAlertAction(title: "Share on Facebook", style: UIAlertActionStyle.Default) { (action) -> Void in
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) {
let facebookComposeVC = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
facebookComposeVC.addImage(self.imageView.image)
self.presentViewController(facebookComposeVC, animated: true, completion: nil)
}
else {
self.showAlert("Flickr Searcher", message: "You are not logged in to your facebook account.")
}
}
// Configure a new action to show the UIActivityViewController
let moreAction = UIAlertAction(title: "More", style: UIAlertActionStyle.Default) { (action) -> Void in
let activityViewController = UIActivityViewController(activityItems: [self.imageView.image!], applicationActivities: nil)
self.presentViewController(activityViewController, animated: true, completion: nil)
}
let dismissAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Destructive) { (action) -> Void in
}
actionSheet.addAction(tweetAction)
actionSheet.addAction(facebookPostAction)
actionSheet.addAction(moreAction)
actionSheet.addAction(dismissAction)
presentViewController(actionSheet, animated: true, completion: nil)
}
// MARK: showAlert
func showAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "Ok", style: .Cancel, handler: { (nil) in
self.dismissViewControllerAnimated(true, completion: nil)
})
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
}
}
My data source:
import UIKit
class PhotoDataSource: NSObject, UICollectionViewDataSource {
//MARK: - Properties
// Array to store the Flickr Photos
var flickrPhotos = [FlickrPhoto]()
// An instance of photoStore.
var photoStore = PhotoStore()
// MARK: - numberOfItemsInSection
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return flickrPhotos.count
}
// MARK: - cellForItemAtIndexPath
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let identifier = "FlickrCell"
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! PhotoCollectionViewCell
let photo = flickrPhotos[indexPath.item]
cell.updateWithImage(photo.image)
print(indexPath.item)
// If you get close to the end of the collection, fetch more photo's.
if indexPath.item == flickrPhotos.count - 20 {
print("Detected the end of the collection")
// Fetch the next batch of photos.
photoStore.fetchPhotosForSearchTerm() {
(photosResult) -> Void in
// Calls the mainthread to update the UI.
NSOperationQueue.mainQueue().addOperationWithBlock() {
switch photosResult {
case let .Success(photos):
print("Successfully found \(photos.count) recent photos.")
self.flickrPhotos.appendContentsOf(photos)
case let .Failure(error):
self.flickrPhotos.removeAll()
print("Error fetching more photos for search term \(error)")
}
collectionView.reloadSections(NSIndexSet(index: 0))
}
}
}
return cell
}
}
This is the method that throws the error. But only when navigated to the detail view first. Staying in the collection view the method gets call over and over with no problem:
photoStore.fetchPhotosForSearchTerm() {
(photosResult) -> Void in
// Calls the mainthread to update the UI.
NSOperationQueue.mainQueue().addOperationWithBlock() {
switch photosResult {
case let .Success(photos):
print("Successfully found \(photos.count) recent photos.")
self.flickrPhotos.appendContentsOf(photos)
case let .Failure(error):
self.flickrPhotos.removeAll()
print("Error fetching more photos for search term \(error)")
}
collectionView.reloadSections(NSIndexSet(index: 0))
}
}

Data not updating to current user when new user logs in using Swift and Parse

Im working on an app that uses phone number and SMS verification to login. It all works well except for one small issue. If I logout of one user, then login with another, the previous users data is loaded, however a new user is created but the previous users data is displayed. I have to logout and login the new user again to load their data. Anybody see whats going on?
Login code:
class LoginViewController: UIViewController {
func displayAlert(title: String, message: String) {
var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action) -> Void in
}))
self.presentViewController(alert, animated: true, completion: nil)
}
#IBOutlet weak var instructionLabel: UILabel!
#IBOutlet weak var phoneNumberTextField: UITextField!
#IBOutlet weak var sendCodeButton: UIButton!
var phoneNumber: String = ""
override func viewDidLoad() {
super.viewDidLoad()
first()
self.editing = true
}
func first() {
phoneNumber = ""
phoneNumberTextField.placeholder = "555-555-5555"
instructionLabel.text = "Enter your phone number to login or sign up"
sendCodeButton.enabled = true
}
func second() {
phoneNumber = phoneNumberTextField.text!
phoneNumberTextField.text = ""
phoneNumberTextField.placeholder = "1234"
instructionLabel.text = "Enter your 4 digit security code"
sendCodeButton.enabled = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
phoneNumberTextField.becomeFirstResponder()
}
#IBAction func didTapSendCodeButton() {
let preferredLanguage = NSBundle.mainBundle().preferredLocalizations[0]
let textFieldText = phoneNumberTextField.text ?? ""
if phoneNumber == "" {
if (preferredLanguage == "en" && textFieldText.characters.count != 10) {
displayAlert("Phone Login", message: NSLocalizedString("warningphone", comment: "You must enter a 10 digit US phone number including area code"))
return first()
}
self.editing = false
let params = ["phoneNumber" : textFieldText, "language" : preferredLanguage]
PFCloud.callFunctionInBackground("sendCode", withParameters: params) { response, error in
self.editing = true
if let error = error {
var description = error.description
if description.characters.count == 0 {
description = NSLocalizedString("warningGeneral", comment: "Something went Wrong. Please try again")
} else if let message = error.userInfo["error"] as? String {
description = message
}
self.displayAlert("Login Error", message: description)
return self.first()
}
return self.second()
}
} else {
if textFieldText.characters.count == 4, let code = Int(textFieldText) {
return doLogin(phoneNumber, code: code)
}
displayAlert("Code Entry", message: NSLocalizedString("warningCodeLength", comment: "You must enter the 4 digit code texted to your number"))
}
}
func doLogin(phoneNumber: String, code: Int) {
self.editing = false
let params = ["phoneNumber": phoneNumber, "codeEntry": code] as [NSObject:AnyObject]
PFCloud.callFunctionInBackground("logIn", withParameters: params) { response, error in
if let description = error?.description {
self.editing = true
return self.displayAlert("Login Error", message: description)
}
if let token = response as? String {
PFUser.becomeInBackground(token) { user, error in
if let _ = error{
self.displayAlert("Login Error", message: NSLocalizedString("warningGeneral", comment: "Something happened while logging in. Please try again"))
self.editing = true
return self.first()
}
return self.dismissViewControllerAnimated(true, completion: nil)
}
} else {
self.editing = true
self.displayAlert("Login Error", message: NSLocalizedString("warningGeneral", comment: "Something went wrong. Please try again"))
return self.first()
}
}
}
override func setEditing(editing: Bool, animated: Bool) {
sendCodeButton.enabled = editing
phoneNumberTextField.enabled = editing
if editing {
phoneNumberTextField.becomeFirstResponder()
}
}
}
extension LoginViewController : UITextFieldDelegate {
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.didTapSendCodeButton()
return true
}
}
Found the problem I had to update the label in viewWillAppear

Add initial note

I am looking at adding an inital note to the note page within my app. this is so that when people click to the notes part there will be some detail on how to use it rather than just a big empty screen. I have no idea where to implement this though. Could you please help, below is the page where it talks about the dictionaries.
import UIKit
import MessageUI
class DetailViewController: UIViewController, MFMailComposeViewControllerDelegate, UITextViewDelegate {
#IBOutlet weak var tView: UITextView!
#IBAction func BarButton(sender: UIBarButtonItem) {
let textToShare = ""
if let myWebsite = NSURL(string: "")
{
let objectsToShare = [textToShare, myWebsite]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
self.presentViewController(activityVC, animated: true, completion: nil)
}
OpenMail()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tView.text = (allNotes[currentNoteIndex] as Note).note
tView.becomeFirstResponder()
// Set controller as swipe gesture recogniser, to allow keyboard dismissal for text box
var swipe: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "dismissKeyboard")
swipe.direction = UISwipeGestureRecognizerDirection.Down
self.view.addGestureRecognizer(swipe)
self.tView.delegate = self
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if tView.text == "" {
allNotes.removeAtIndex(currentNoteIndex)
}
else {
(allNotes[currentNoteIndex] as Note).note = tView.text
}
Note.saveNotes()
noteTable?.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
// Open mail controller on screen and prepare with preset values.
let mailComposerVC = MFMailComposeViewController()
var MessageText: String!
MessageText = tView.text
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients([""])
mailComposerVC.setSubject("")
mailComposerVC.setMessageBody(MessageText, isHTML: false)
return mailComposerVC
}
func showSendMailErrorAlert() {
// Alert user to email error
let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
sendMailErrorAlert.show()
}
// MARK: MFMailComposeViewControllerDelegate Method
func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
func OpenMail() {
//Function to open mail composer on screen
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.presentViewController(mailComposeViewController, animated: true, completion: nil)
} else {
self.showSendMailErrorAlert()
}
}
func dismissKeyboard() {
// Dismiss keyboard for textfield
self.tView.resignFirstResponder()
}
}
note.swift
import UIKit
var allNotes:[Note] = []
var currentNoteIndex:NSInteger = -1
var noteTable:UITableView?
let KAllNotes:String = "notes"
class Note: NSObject {
var date:String
var note:String
override init() {
date = NSDate().description
note = ""
}
func dictionary() -> NSDictionary {
return ["note":note, "date":date]
}
class func saveNotes() {
var aDictionaries:[NSDictionary] = []
for (var i:NSInteger = 0; i < allNotes.count; i++) {
aDictionaries.append(allNotes[i].dictionary())
}
NSUserDefaults.standardUserDefaults().setObject(aDictionaries, forKey: KAllNotes)
// aDictionaries.writeToFile(filePath(), atomically: true)
}
class func loadnotes() {
allNotes.removeAll(keepCapacity: true)
var defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
var savedData:[NSDictionary]? = defaults.objectForKey(KAllNotes) as? [NSDictionary]
// var savedData:NSArray? = NSArray(contentsOfFile: filePath())
if let data:[NSDictionary] = savedData {
for (var i:NSInteger = 0; i < data.count; i++) {
var n:Note = Note()
n.setValuesForKeysWithDictionary(data[i] as [NSObject : AnyObject])
allNotes.append(n)
}
}
}
class func filePath() -> String {
var d:[String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
if let directories:[String] = d {
var docsDirectory:String = directories[0]
var path:String = docsDirectory.stringByAppendingPathComponent("\(KAllNotes).notes")
return path;
}
return ""
}
}
Thanks in advance
Sam
Add an NSUserDefault boolean that stores whether or not the initial note should be shown, e.g. that the app has been launched for the first time. Then load an initial note accordingly. When a note is added or the initial note is deleted, then change the boolean accordingly so the initial note doesn't show up next time.
You could also initialize your database with an initial note. Not clear from your code how the notes are saved, but this approach would probably rely on the NSUserDefault approach above, except it could be done in the AppDelegate or something.
example:
let InitialSetupComplete = "InitialSetupComplete" // Note: I would define this at the top of a file
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.boolForKey(InitialSetupComplete) {
// Show initial note
}
// Later on when the note is deleted, or modified (or immediately after initial note loaded into the database, see below)
defaults.setBool(true, forKey: InitialSetupComplete)
Would be easier/cleaner just to initialize your database with the initial note in the app delegate (e.g. call within applicationDidFinishLaunching), so your view controller doesn't have to figure this out. Similar code, except you would use setBool right away after the initial note has been saved to the database. I don't know anything about your database from the question, so can't really provide a more detailed example than this. Hope this helps.

Resources