I am creating app which will sent notification daily about taking pills. I have question how to cancel(turn off) local notification, when I delete the pill(cell).
If you know some other ways to fix this, I will glad to see
Thank u!
https://imgur.com/a/dinUsTY - Here is the images of app
// FirstViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let navController = segue.destination as? UINavigationController else { return }
guard let setPill = navController.topViewController as? SetPillsTableViewController else { return }
setPill.pill = sender as? PillList
}
#IBAction func unwind (for segue: UIStoryboardSegue) {
guard let setPillVC = segue.source as? SetPillsTableViewController else { return }
let pill = PillList(value: [setPillVC.pillNameTF.text ?? "",
setPillVC.pillNoteTF.text ?? "",
setPillVC.datePickerLb.text ?? "",
setPillVC.datePicker.date
])
if isEdit{
StorageManager.shared.save(pill)
setPillVC.notificationSent()
setPillVC.showAlert(title: "Поздравляем!", message: "Уведомления будут приходить каждый день")
} else {
guard let index = tableView.indexPathForSelectedRow else { return }
StorageManager.shared.edit(pills[index.row], newName: pill.name, newNote: pill.note, newTime: pill.time, newDate: pill.date)
setPillVC.notificationSent()
}
tableView.reloadData()
}
// SecondViewController
var id = NSUUID().uuidString
func notificationSent() {
let dateComponents = Calendar.current.dateComponents([.hour, .minute], from: datePicker.date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let content = UNMutableNotificationContent()
content.title = "Пожалуйста примите таблетки"
content.body = "\(pillNameTF.text ?? ""): \(pillNoteTF.text ?? "")"
content.categoryIdentifier = "notifyAboutPill"
content.sound = UNNotificationSound.default
let request = UNNotificationRequest(identifier: id,
content: content,
trigger: trigger)
center.add(request)
}
func deleteNotification() {
center.removePendingNotificationRequests(withIdentifiers: [id])
// I don't have any idea where I can paste this method.
}
I have a tableview in my view controller and i am trying to implement the pull to refresh function. When i pull to refresh the table view does not reload and the data is not updated.
When i print the array print(tempRefresh) inside of my fetchRefresh function, it returns an empty array??
my firebase database looks like this.
override func viewDidLoad() {
super.viewDidLoad()
// refresh the page
refreshControl = UIRefreshControl()
if #available(iOS 10.0, *) {
tableView.refreshControl = refreshControl
} else {
// fallback on older versions
tableView.addSubview(refreshControl)
}
refreshControl.attributedTitle = NSAttributedString(string: "Loading...")
refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged)
// reload the tabelview
tableView.reloadData()
tableView.delegate = self
tableView.dataSource = self
}
#objc func handleRefresh() {
print("refresh")
beginRefresh()
DispatchQueue.main.async {
self.refreshControl.endRefreshing()
}
}
func fetchRefresh(completion: #escaping(_ comments:[Comments])->()) {
oldCommentsQuery.queryLimited(toLast: 20).observeSingleEvent(of: .value, with: { snapshot in
var tempRefresh = [Comments]()
let commentsSnap = snapshot.childSnapshot(forPath: "comments")
let allComments = commentsSnap.children.allObjects as! [DataSnapshot]
for commentSnap in allComments {
let degree = commentSnap.childSnapshot(forPath: "reply degree").value as? String ?? ""
let name = commentSnap.childSnapshot(forPath: "reply name").value as? String ?? ""
let text = commentSnap.childSnapshot(forPath: "reply text").value as? String ?? ""
let university = commentSnap.childSnapshot(forPath: "reply university").value as? String ?? ""
let photoURL = commentSnap.childSnapshot(forPath: "reply url").value as? String ?? ""
let url = URL(string: photoURL)
let timestamp = commentSnap.childSnapshot(forPath: "timestamp").value as? Double
let lastComment = self.comments.last
if snapshot.key != lastComment?.id {
let newRefresh = Comments(id: snapshot.key, fullname: name, commentText: text, university: university, degree: degree, photoURL: photoURL, url: url!, timestamp: timestamp!)
tempRefresh.insert(newRefresh, at: 0)
//test
print(tempRefresh)
}
}
return completion(tempRefresh)
})
}
func beginRefresh() {
fetchingMore = true
// fetch the comments
fetchRefresh { newComments in
self.comments.append(contentsOf: newComments)
self.endReached = newComments.count == 0
self.fetchingMore = false
self.tableView.reloadData()
}
}
I am using google place api to get location in my swift application. In my app when i am going to place api screen by clicking on the textfield present inside the cell of my tableview it is working fine. But when i am using the same code to show the place api screen by clicking on the textfield present inside the uiview, after selecting any place it is comming back to the previous screen, but once again the place api screen opening automatically. i have added my code, can anyonce see it and let me know the solution?
import GooglePlaces
class AddPatientViewController: UIViewController{
//MARK:- Properties
#IBOutlet weak var location_TextField: UITextField!
//MARK:- Variables
var locationManager = CLLocationManager()
var mAppDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate;
//MARK:- LifeCycles Methods
override func viewDidLoad() {
super.viewDidLoad()
setDelegate()
}
//MARK:- Helpers
private func setDelegate(){
location_TextField.delegate = self
}
//MARK: - getLocation
func getCurrentLatLongFromCLlocation() {
locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
switch CLLocationManager.authorizationStatus() {
case .notDetermined, .restricted, .denied:
print("No access")
getPermissionAgain()
case .authorizedAlways, .authorizedWhenInUse:
print("Access")
if let coordinateValue = locationManager.location?.coordinate {
mAppDelegate.cordinateVal = coordinateValue
self.getPlaceDataUsingLocation()
}
#unknown default:
getPermissionAgain()
}
} else {
print("Location services are not enabled")
getPermissionAgain()
}
}
func getPermissionAgain(){
let alert = UIAlertController(title: "Simplr", message: "Required location permission to set your search location", preferredStyle: .alert)
let okayAction = UIAlertAction(title: "Dismiss", style: .default, handler: nil)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (action) in
if let appSettings = URL(string: UIApplication.openSettingsURLString) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(appSettings, options: [:], completionHandler: { (enabled) in
DispatchQueue.main.async {
//UIApplication.shared.registerForRemoteNotifications()
}
})
} else {
// Fallback on earlier versions
}
}
}
alert.addAction(okayAction)
alert.addAction(settingsAction)
present(alert, animated: false, completion: nil)
}
func getPlaceDataUsingLocation(){
DispatchQueue.global().async {
// Specify the place data types to return.
let placesClient = GMSPlacesClient.init()
let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.name.rawValue) |
UInt(GMSPlaceField.placeID.rawValue) | UInt(GMSPlaceField.coordinate.rawValue) | UInt(GMSPlaceField.formattedAddress.rawValue))
placesClient.currentPlace { (list, error) in
if let error = error {
print("An error occurred: \(error.localizedDescription)")
return
}
if let placeLikelihoodList = list?.likelihoods {
for likelihood in placeLikelihoodList {
let place = likelihood.place
print("\n\n")
print("Current Place name \(String(describing: place.name)) at likelihood \(likelihood.likelihood)")
print("Current PlaceID \(String(describing: place.placeID))")
print("Formatted Address: \(String(describing: place.formattedAddress))")
// print("Fields: \(place.)")
print("\nAddress Component: \(String(describing: place.addressComponents))\n")
print("Type: \(String(describing: place.types))")
}
}
}
}
}
}
//MARK: - UITextfield Delegate Methods
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{
if textField == location_TextField{
let autocompleteController = GMSAutocompleteViewController()
autocompleteController.delegate = self
// autocompleteController.primaryTextColor = UIColor(hex: "#4C2B6D")
// autocompleteController.secondaryTextColor = UIColor(hex: "#4C2B6D")
// Specify the place data types to return.
let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.name.rawValue) |
UInt(GMSPlaceField.placeID.rawValue) | UInt(GMSPlaceField.coordinate.rawValue) |
UInt(GMSPlaceField.formattedAddress.rawValue) | UInt(GMSPlaceField.addressComponents.rawValue))
autocompleteController.placeFields = fields
autocompleteController.navigationController?.navigationBar.barTintColor = .blue
autocompleteController.navigationController?.navigationBar.prefersLargeTitles = true
// Specify a filter.
let filter = GMSAutocompleteFilter()
filter.type = .geocode
autocompleteController.autocompleteFilter = filter
// Display the autocomplete view controller.
autocompleteController.modalPresentationStyle = .fullScreen
present(autocompleteController, animated: true, completion: nil)
}
return true
}
}
//MARK: - GMSAutocompleteViewControllerDelegate
#available(iOS 13.0, *)
extension AddPatientViewController: GMSAutocompleteViewControllerDelegate {
// Handle the user's selection.
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
print("selected place is \(getFormattedAddressFromAddressComponents(place: place))")
location_TextField.text = getFormattedAddressFromAddressComponents(place: place)
self.dismiss(animated: true)
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
// TODO: handle the error.
print("Error: ", error.localizedDescription)
}
// User canceled the operation.
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
self.dismiss(animated: true)
}
// Turn the network activity indicator on and off again.
func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
func getFormattedAddressFromAddressComponents(place: GMSPlace) -> String{
var neighborhood = ""
var locality = ""
var sublocality = ""
var administrative_area_level_1 = ""
var formatedAddress = ""
if let addressComponents : Array<GMSAddressComponent> = place.addressComponents{
print(addressComponents)
for component in addressComponents{
if component.types.contains("administrative_area_level_1"){
if let shortName = component.shortName{
administrative_area_level_1 = shortName
}
}
else if component.types.contains("neighborhood")
{
neighborhood = component.name
} else if component.types.contains("sublocality")
{
sublocality = component.name
}else if component.types.contains("locality")
{
locality = component.name
}
}
var shouldAddComma = false
if !isNullObject(anyObject: administrative_area_level_1){
shouldAddComma = true
}
if !isNullObject(anyObject: neighborhood){
formatedAddress = neighborhood
}else if !isNullObject(anyObject: sublocality){
formatedAddress = sublocality
}
else if !isNullObject(anyObject: locality){
formatedAddress = locality
}
if !isNullObject(anyObject: formatedAddress){
if shouldAddComma{
formatedAddress = "\(formatedAddress),\(administrative_area_level_1)"
}
}
}
return formatedAddress
}
}
Hello I want to add a button action to my UNMutableNotification but I do not understand why it does not work, yet I passed him the catergoryIdentifier.
My code:
class LocalNotification: NSObject {
class func createToDate(identifier: String,
title: String,
subtitle: String = "",
body: String,
to date: Date,
sound: UNNotificationSound = .default,
repeatNotification: Bool = false,
completion: #escaping (_ error: Error?) -> ()) {
let content = UNMutableNotificationContent()
content.title = title
content.subtitle = subtitle
content.body = body
content.sound = sound
content.categoryIdentifier = "fittoCateroy"
let dateComponent = Calendar.current.dateComponents([.day, .hour, .minute], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: repeatNotification)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
completion(error)
}
}
class func withAction() {
let snoozeAction = UNNotificationAction(identifier: "snooze", title: "Snooze", options: [])
let category = UNNotificationCategory(identifier: "fittoCateroy", actions: [snoozeAction], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
createToDate(identifier: "M",
title: "My title", subtitle: "Sub", body: "Body",
to:Date().adding(seconds: 10), sound: .default, repeatNotification: false) { error in
if let error = error {
print("ERRRRROR \(error.localizedDescription)")
}
}
}
}
When I call from my controller the function createToDate() the notification work, but if I call the function withAction(), the notification does not work.
The Date().adding(second: 10) is a custom extension
I am using this library for Swift forms: https://github.com/ortuman/SwiftForms This is very similar to Eureka.
Here's an explanation of what I am trying to do:
I have 2 Pickers in my form. Picker1 is just a normal picker while Picker2 depends on the value of Picker1. So when the user changes the value of Picker1. Options in Picker2 should be changed also. To do this, here's my function:
func change_data(){
row4.configuration[FormRowDescriptor.Configuration.Options] = ["hello", "from", "the"]
row4.value = "hello"
self.tableView.reloadData()
}
I use the reloadData() to see the changes in the values of my 2 pickers. But unfortunately, I get the error: assertion failed: self.form property MUST be assigned!
I tried putting that code in the action of a button in top bar and it works.
func submit(_: UIBarButtonItem!) {
//let message = self.form.formValues().description
//let alert: UIAlertView = UIAlertView(title: "Form output", message: message, delegate: nil, cancelButtonTitle: "OK")
//alert.show()
row4.configuration[FormRowDescriptor.Configuration.Options] = ["hello", "from", "the"]
row4.value = "hello"
self.tableView.reloadData()
}
But I need to call the reloadData() inside my function and not in button click.
Here's the viewDidLoad of my FormViewController:
public override func viewDidLoad() {
super.viewDidLoad()
assert(form != nil, "self.form property MUST be assigned!")
navigationItem.title = form.title
}
What I am trying to accomplish is this:
I have several pickers, and the last picker will depend on the chosen items from 2nd and 3rd. I call those functions to update the content of my last picker.
Here's my FormViewController class:
import UIKit
import CoreData
import SwiftForms
class ExampleFormViewController: FormViewController {
struct Static {
static let nameTag = "name"
static let passwordTag = "password"
static let lastNameTag = "lastName"
static let jobTag = "job"
static let emailTag = "email"
static let URLTag = "url"
static let phoneTag = "phone"
static let enabled = "enabled"
static let check = "check"
static let segmented = "segmented"
static let picker = "picker"
static let birthday = "birthday"
static let categories = "categories"
static let button = "button"
static let stepper = "stepper"
static let slider = "slider"
static let textView = "textview"
}
var val_territory = [Int]()
var val_company = [Int]()
var val_facility = [Int]()
var val_specialty = [Int]()
var putu_company = ""
var putu_territory = ""
var putu_facility = ""
var str_territory = [String]()
var str_company = [String]()
var str_facility = [String]()
var str_specialty = [String]()
var territory: [Territory] = []
var company: [Company] = []
var facility: [Facility] = []
var specialty: [Specialty] = []
var row1 = FormRowDescriptor(tag: Static.picker, rowType: .Picker, title: "Territory")
var row2 = FormRowDescriptor(tag: Static.picker, rowType: .Picker, title: "Company")
var row3 = FormRowDescriptor(tag: Static.picker, rowType: .Picker, title: "Facility")
var row4 = FormRowDescriptor(tag: Static.picker, rowType: .Picker, title: "Specialty")
let name: String
var form2 = FormDescriptor(title: "Create Shift Entry")
init(_ coder: NSCoder? = nil) {
name = "Bar"
if let coder = coder {
super.init(coder: coder)
} else {
super.init(nibName: nil, bundle:nil)
}
}
required convenience init(coder: NSCoder) {
self.init(coder)
load_data()
self.loadForm()
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .Plain, target: self, action: "submit:")
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "cancel:")
}
// MARK: Actions
func submit(_: UIBarButtonItem!) {
//let message = self.form.formValues().description
//let alert: UIAlertView = UIAlertView(title: "Form output", message: message, delegate: nil, cancelButtonTitle: "OK")
//alert.show()
row4.configuration[FormRowDescriptor.Configuration.Options] = ["hello", "from", "the"]
row4.value = "hello"
self.tableView.reloadData()
}
func cancel(_: UIBarButtonItem!) {
self.performSegueWithIdentifier("goto_main2", sender: self)
}
private func loadForm() {
let form = FormDescriptor(title: "Create Shift Entry")
let section1 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil)
row1.configuration[FormRowDescriptor.Configuration.Options] = str_territory
row1.value = str_territory[0]
section1.addRow(row1)
row2.configuration[FormRowDescriptor.Configuration.Options] = str_company
row2.value = str_company[0]
section1.addRow(row2)
row3.configuration[FormRowDescriptor.Configuration.Options] = str_facility
row3.value = str_facility[0]
section1.addRow(row3)
row4.configuration[FormRowDescriptor.Configuration.Options] = str_specialty
row4.value = str_specialty[0]
section1.addRow(row4)
let section2 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil)
var row = FormRowDescriptor(tag: Static.phoneTag, rowType: .Phone, title: "Scheduled Hours")
row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.placeholder" : "e.g. 8", "textField.textAlignment" : NSTextAlignment.Right.rawValue]
section2.addRow(row)
let section3 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil)
row = FormRowDescriptor(tag: Static.birthday, rowType: .DateAndTime, title: "Time In")
section3.addRow(row)
row = FormRowDescriptor(tag: Static.birthday, rowType: .DateAndTime, title: "Time Out")
section3.addRow(row)
let section4 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil)
row = FormRowDescriptor(tag: Static.enabled, rowType: .BooleanSwitch, title: "Missed Lunch")
section4.addRow(row)
let section5 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil)
row = FormRowDescriptor(tag: Static.textView, rowType: .MultilineText, title: "Notes")
section5.addRow(row)
let section8 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil)
row = FormRowDescriptor(tag: Static.button, rowType: .Button, title: "Add Staff Signature")
row.configuration[FormRowDescriptor.Configuration.DidSelectClosure] = {
self.view.endEditing(true)
} as DidSelectClosure
section8.addRow(row)
let section9 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil)
row = FormRowDescriptor(tag: Static.button, rowType: .Button, title: "Add Supervisor Signature")
row.configuration[FormRowDescriptor.Configuration.DidSelectClosure] = {
self.view.endEditing(true)
} as DidSelectClosure
section9.addRow(row)
form.sections = [section1, section2, section3, section4, section5, section8, section9]
self.form = form
form2 = form
}
func load_data(){
let sortDescriptor = NSSortDescriptor(key: "orig_id", ascending: true)
let sortDescriptors = [sortDescriptor]
let facilityPredicate = NSPredicate(format: "facility = %#", NSNumber(integer: 1))
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext
let fetchRequest = NSFetchRequest(entityName:"Company")
fetchRequest.sortDescriptors = sortDescriptors
let fetchRequestTerritory = NSFetchRequest(entityName:"Territory")
fetchRequestTerritory.sortDescriptors = sortDescriptors
let fetchRequestFacility = NSFetchRequest(entityName:"Facility")
fetchRequestFacility.sortDescriptors = sortDescriptors
let fetchRequestSpecialty = NSFetchRequest(entityName:"Specialty")
fetchRequestSpecialty.sortDescriptors = sortDescriptors
fetchRequestSpecialty.predicate = facilityPredicate
let error:NSError
do {
let company_temp = try context.executeFetchRequest(fetchRequest)
company = company_temp as! [Company]
for t in company {
val_company.append(t.orig_id! as Int)
str_company.append(t.name! as String)
}
print(company.count)
let territory_temp = try context.executeFetchRequest(fetchRequestTerritory)
territory = territory_temp as! [Territory]
for t in territory {
val_territory.append(Int(t.orig_id!)!)
str_territory.append(t.name! as String)
}
print(territory_temp.count)
let facility_temp = try context.executeFetchRequest(fetchRequestFacility)
facility = facility_temp as! [Facility]
for t in facility {
val_facility.append(Int(t.orig_id!)!)
str_facility.append(t.name! as String)
}
print(facility_temp.count)
let specialty_temp = try context.executeFetchRequest(fetchRequestSpecialty)
specialty = specialty_temp as! [Specialty]
for t in specialty {
val_specialty.append(Int(t.orig_id!)!)
str_specialty.append(t.name! as String)
}
print(specialty_temp.count)
} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}
}
func get_facility_ter(company: Int!){
//print("company: " + company)
//print("territory: " + territory!)
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext
let sortDescriptor = NSSortDescriptor(key: "orig_id", ascending: true)
let sortDescriptors = [sortDescriptor]
let fetchRequest = NSFetchRequest(entityName:"Territory")
fetchRequest.sortDescriptors = sortDescriptors
do {
let territory_temp = try context.executeFetchRequest(fetchRequest)
var territory2 = territory_temp as! [Territory]
for t in territory2 {
val_territory.append(Int(t.orig_id!)!)
str_territory.append(t.name! as String)
}
} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}
if let company2 = company{
let companyPredicate = NSPredicate(format: "company = %#", NSNumber(integer: val_territory[str_territory.indexOf(putu_territory)!]))
let territoryPredicate = NSPredicate(format: "territory = %#", NSNumber(integer: val_territory[company]))
let predicate = NSCompoundPredicate(type: NSCompoundPredicateType.OrPredicateType, subpredicates: [companyPredicate, territoryPredicate])
let fetchRequestFacility = NSFetchRequest(entityName:"Facility")
fetchRequestFacility.predicate = predicate
print(companyPredicate)
do {
let facility_temp = try context.executeFetchRequest(fetchRequestFacility)
facility = facility_temp as! [Facility]
str_facility.removeAll()
val_facility.removeAll()
for t in facility {
val_facility.append(Int(t.orig_id!)!)
str_facility.append(t.name! as String)
}
row3.configuration[FormRowDescriptor.Configuration.Options] = str_facility
} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}
}
}
func get_facility_com(company: Int!){
//print("company: " + company)
//print("territory: " + territory!)
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext
let sortDescriptor = NSSortDescriptor(key: "orig_id", ascending: true)
let sortDescriptors = [sortDescriptor]
let fetchRequest = NSFetchRequest(entityName:"Company")
fetchRequest.sortDescriptors = sortDescriptors
do {
let company_temp = try context.executeFetchRequest(fetchRequest)
var company2 = company_temp as! [Company]
for t in company2 {
val_company.append(t.orig_id! as Int)
str_company.append(t.name! as String)
}
} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}
print(val_company.count)
print(str_company.count)
print(putu_company)
print(str_company)
print(str_company.contains(putu_company))
if let company2 = company{
let companyPredicate = NSPredicate(format: "company = %#", NSNumber(integer: val_company[company]))
let territoryPredicate = NSPredicate(format: "territory = %#", NSNumber(integer: val_company[str_company.indexOf(putu_company)!]))
let predicate = NSCompoundPredicate(type: NSCompoundPredicateType.OrPredicateType, subpredicates: [companyPredicate, territoryPredicate])
let fetchRequestFacility = NSFetchRequest(entityName:"Facility")
fetchRequestFacility.predicate = predicate
print(companyPredicate)
do {
let facility_temp = try context.executeFetchRequest(fetchRequestFacility)
facility = facility_temp as! [Facility]
str_facility.removeAll()
val_facility.removeAll()
for t in facility {
val_facility.append(Int(t.orig_id!)!)
str_facility.append(t.name! as String)
}
row3.configuration[FormRowDescriptor.Configuration.Options] = str_facility
} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}
}
}
func get_specialty(facility_txt: Int!){
print("VALUE OF FACILITY: " + String(facility_txt))
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext
let sortDescriptor = NSSortDescriptor(key: "orig_id", ascending: true)
let sortDescriptors = [sortDescriptor]
let facilityPredicate = NSPredicate(format: "facility = %#", NSNumber(integer: val_facility[str_facility.indexOf(putu_facility)!]))
let fetchRequestSpecialty = NSFetchRequest(entityName:"Specialty")
fetchRequestSpecialty.sortDescriptors = sortDescriptors
fetchRequestSpecialty.predicate = facilityPredicate
do {
let specialty_temp = try context.executeFetchRequest(fetchRequestSpecialty)
specialty = specialty_temp as! [Specialty]
str_specialty.removeAll()
val_specialty.removeAll()
for t in specialty {
val_specialty.append(Int(t.orig_id!)!)
str_specialty.append(t.name! as String)
}
print(str_specialty)
self.form = form2
row4.configuration[FormRowDescriptor.Configuration.Options] = str_specialty
row4.value = "hello"
self.tableView.reloadData()
} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}
}
func put_company(putu: String!, row: Int!){
print("haler")
putu_company = putu
print(putu_company)
print(row)
get_facility_com(row)
}
func put_territory(putu: String!, row: Int!){
print("haler")
putu_territory = putu
print(putu_territory)
print(row)
get_facility_ter(row)
}
func put_facility(putu: String!, row: Int!){
print("haler")
putu_facility = putu
print(putu_facility)
print(row)
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext
let sortDescriptor = NSSortDescriptor(key: "orig_id", ascending: true)
let sortDescriptors = [sortDescriptor]
let fetchRequestFacility = NSFetchRequest(entityName:"Facility")
fetchRequestFacility.sortDescriptors = sortDescriptors
do {
let facility_temp = try context.executeFetchRequest(fetchRequestFacility)
facility = facility_temp as! [Facility]
for t in facility {
val_facility.append(Int(t.orig_id!)!)
str_facility.append(t.name! as String)
}
} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}
print(val_facility)
get_specialty(val_facility[row])
}
}
I call those functions here:
import UIKit
public class FormPickerCell: FormValueCell, UIPickerViewDelegate, UIPickerViewDataSource {
// MARK: Properties
private let picker = UIPickerView()
private let hiddenTextField = UITextField(frame: CGRectZero)
struct MyVariables {
static var mv_territory = 0
static var mv_company = 0
static var mv_facility = 0
static var mv_specialty = 0
}
// MARK: FormBaseCell
public override func configure() {
super.configure()
accessoryType = .None
picker.delegate = self
picker.dataSource = self
hiddenTextField.inputView = picker
contentView.addSubview(hiddenTextField)
}
public override func update() {
super.update()
titleLabel.text = rowDescriptor.title
if let value = rowDescriptor.value {
valueLabel.text = rowDescriptor.titleForOptionValue(value)
if let options = rowDescriptor.configuration[FormRowDescriptor.Configuration.Options] as? NSArray {
let index = options.indexOfObject(value)
if index != NSNotFound {
picker.selectRow(index, inComponent: 0, animated: false)
}
}
}
}
public override class func formViewController(formViewController: FormViewController, didSelectRow selectedRow: FormBaseCell) {
if selectedRow.rowDescriptor.value == nil {
if let row = selectedRow as? FormPickerCell {
let options = selectedRow.rowDescriptor.configuration[FormRowDescriptor.Configuration.Options] as? NSArray
let optionValue = options?[0] as? NSObject
selectedRow.rowDescriptor.value = optionValue
row.valueLabel.text = selectedRow.rowDescriptor.titleForOptionValue(optionValue!)
row.hiddenTextField.becomeFirstResponder()
}
} else {
if let row = selectedRow as? FormPickerCell {
guard let optionValue = selectedRow.rowDescriptor.value else { return }
row.valueLabel.text = selectedRow.rowDescriptor.titleForOptionValue(optionValue)
row.hiddenTextField.becomeFirstResponder()
}
}
}
// MARK: UIPickerViewDelegate
public func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return rowDescriptor.titleForOptionAtIndex(row)
}
public func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let options = rowDescriptor.configuration[FormRowDescriptor.Configuration.Options] as? NSArray
let optionValue = options?[row] as? NSObject
rowDescriptor.value = optionValue
valueLabel.text = rowDescriptor.titleForOptionValue(optionValue!)
if(rowDescriptor.title == "Company"){
print("company")
print(valueLabel.text)
ExampleFormViewController().put_company(valueLabel.text, row: row)
}else if(rowDescriptor.title == "Territory"){
print("territory")
print(valueLabel.text)
ExampleFormViewController().put_territory(valueLabel.text, row: row)
}
else if(rowDescriptor.title == "Facility"){
print("facility")
print(valueLabel.text)
ExampleFormViewController().put_facility(valueLabel.text, row: row)
}
}
// MARK: UIPickerViewDataSource
public func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if let options = rowDescriptor.configuration[FormRowDescriptor.Configuration.Options] as? NSArray {
return options.count
}
return 0
}
}
I do that to put new values to my picker whenever the selected item in other pickers change.
I believe the error is in FormPickerCell in pickerView:didSelectRow:inComponent: method:
ExampleFormViewController().put_territory(valueLabel.text, row: row)
In this line you are creating a new instance of ExampleFormViewController. And I assume you want to call this function on your existing controller instance.
The easiest (and the wrongest) solution would be to use FormBaseCell. formViewController property:
public func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let options = rowDescriptor.configuration[FormRowDescriptor.Configuration.Options] as? NSArray
let optionValue = options?[row] as? NSObject
rowDescriptor.value = optionValue
valueLabel.text = rowDescriptor.titleForOptionValue(optionValue!)
let controller = formViewController as! ExampleFormViewController
if(rowDescriptor.title == "Company"){
controller.put_company(valueLabel.text, row: row)
} else if(rowDescriptor.title == "Territory"){
controller.put_territory(valueLabel.text, row: row)
} else if(rowDescriptor.title == "Facility"){
controller.put_facility(valueLabel.text, row: row)
}
}
But correct solution for SwiftForm would be to use standard FormPickerCell (don't override it with custom logic just for one controller!) and use row.configuration[FormRowDescriptor.Configuration.DidUpdateClosure]:
private func loadForm() {
let form = FormDescriptor(title: "Create Shift Entry")
let section1 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil)
row1.configuration[FormRowDescriptor.Configuration.Options] = str_territory
row1.value = str_territory[0]
row1.configuration[FormRowDescriptor.Configuration.DidUpdateClosure] = { [weak self] rowDescriptor in
guard let value = rowDescriptor.value else { return }
guard let options = rowDescriptor.configuration[FormRowDescriptor.Configuration.Options] as? NSArray else { return }
let index = options.indexOfObject(value)
self?.put_territory(rowDescriptor.titleForOptionValue(value), row: index)
}
section1.addRow(row1)
/// add corresponding DidUpdateClosure for row2 and row3
/// ...
}