UITableView and UITableViewCell Swift - objective-c

I am working with Swift and am having a problem loading saved data into UITableView custom cell. I have created a ViewController/ TableViewController and TableViewCell. The form data is saving and is displayed in console. The problem is, nothing gets returned when going back to TableView (My list). I have created labels in the custom cell and everything seems to be linked correctly, but nothing is being displayed.. Am I missing something?
Here is the code from my ViewController:
import UIKit
import CoreData
class DetailsViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate {
var cell:UITableViewCell?
#IBOutlet var txtPTitle: UITextField!
#IBOutlet var txtPDesc: UITextField!
#IBOutlet var txtSDate: UITextField!
#IBOutlet var txtEDate: UITextField!
// Add our date picker keyboard on Project Start Date
#IBAction func dp(sender: UITextField!) {
var datePickerView : UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Date
sender.inputView = datePickerView
datePickerView.addTarget(self, action: Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged)
}
func handleDatePicker(sender: UIDatePicker) {
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM dd yyyy"
txtSDate.text = dateFormatter.stringFromDate(sender.date)
}
#IBAction func dp2(sender: UITextField!) {
var datePickerView : UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Date
sender.inputView = datePickerView
datePickerView.addTarget(self, action: Selector("handleDatePicker2:"), forControlEvents: UIControlEvents.ValueChanged)
}
func handleDatePicker2(sender: UIDatePicker) {
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM dd yyyy"
txtEDate.text = dateFormatter.stringFromDate(sender.date)
}
var project: String = ""
var desc: String = ""
var sdate: String = ""
var edate: String = ""
var existingItem: NSManagedObject!
override func viewDidLoad() {
super.viewDidLoad()
if (existingItem != nil) {
txtPTitle.text = project
txtPDesc.text = desc
txtSDate.text = sdate
txtEDate.text = edate
}
//Do any additional setup after loading the view.
txtPTitle.delegate = self
txtPDesc.delegate = self
txtSDate.delegate = self
txtEDate.delegate = self
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
textField.resignFirstResponder()
txtPDesc.resignFirstResponder()
return true
}
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
self.view.endEditing(true)
}
#IBAction func savedTapped(sender: AnyObject) {
// Reference to our app delegate
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
// Reference moc
let contxt: NSManagedObjectContext = appDel.managedObjectContext!
let en = NSEntityDescription.entityForName("ProjectTask", inManagedObjectContext: contxt)
// Check if task exists
if (existingItem != nil) {
existingItem.setValue(txtPTitle.text as String, forKey: "project")
existingItem.setValue(txtPDesc.text as String, forKey: "desc")
existingItem.setValue(txtSDate.text as String, forKey: "sdate")
existingItem.setValue(txtEDate.text as String, forKey: "edate")
} else {
// Create instance of our data model and initialize
var newItem = Model(entity: en, insertIntoManagedObjectContext: contxt)
// Map our properties
newItem.project = txtPTitle.text
newItem.desc = txtPDesc.text
newItem.sdate = txtSDate.text
newItem.edate = txtEDate.text
println(newItem)
}
// Save our context
contxt.save(nil)
// Navigate back to root view controller
self.navigationController.popToRootViewControllerAnimated(true)
}
#IBAction func cancel(sender: AnyObject) {
// Navigate back to root view controller
self.navigationController.popToRootViewControllerAnimated(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Here is the code from my TableViewController:
import UIKit
import CoreData
class ListTableViewController: UITableViewController, UITableViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
//Register Our Custom Table Cell //
self.tableView.registerClass(ProjectTableViewCell.self, forCellReuseIdentifier: "projectlist")
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell = tableView.dequeueReusableCellWithIdentifier("projectlist", forIndexPath: indexPath) as ProjectTableViewCell
cell.projectLabel.text = "project"
return cell
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
Here is the code from the TableViewCell
import UIKit
import CoreData
class ProjectTableViewCell: UITableViewCell {
#IBOutlet var projectLabel: UILabel! = UILabel()
#IBOutlet var descriptionLabel: UILabel! = UILabel()
#IBOutlet var sdateLabel: UILabel! = UILabel()
#IBOutlet var edateLabel: UILabel! = UILabel()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
I also have another for NSManagedObject
import UIKit
import CoreData
#objc(Model)
class Model: NSManagedObject {
//Properties feed of attributes on our database - Must match the database attributes
#NSManaged var project: String
#NSManaged var desc: String
#NSManaged var sdate: String
#NSManaged var edate: String
}
Is there something I am missing here? This is driving me crazy. I read that this should be added to the tableviewcell, but I keep getting error this error: tableviewcell does not implement its superclass's required members
init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: UITableViewCellStyle.Value1, reuseIdentifier: reuseIdentifier)
}

Your problem is that you're registering the class -- you should only do that if you create the cell entirely in code (that is, the subviews are created programmatically). If you made the cell in the storyboard, don't register anything. If you made it in a xib, then register the nib. All those lines like,
#IBOutlet var projectLabel: UILabel! = UILabel()
don't make sense. You're creating a new label with no frame, but I assume you already created theses labels in IB somewhere (since you're using IBOutlets). If you did create them in IB, then those lines should be like so,
#IBOutlet var projectLabel: UILabel!

Please replace your init in TableViewCell class with following -
required init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}

Related

how do I link a button to the webview of another controller having a link that changes based on the cell pressed?

I have a button that needs to open a web view on another controller in modally. currently the button executes the code you see below. I would like the button to open the webview directly. the link changes because it is an rss reader and therefore, based on the cell pressed, changes the link of the button that must open the webview.
this is the code that manages the controller that appears after the cell has been pressed
class FeedItemWebViewController: UIViewController, UIWebViewDelegate {
#IBOutlet weak var textView: UITextView!
var link: String? = nil
var descriptionTesto:String? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.textView.text = descriptionTesto
}
#IBAction func apri(_ sender: UIBarButtonItem) {
guard let url = URL(string: self.link ?? "") else { return }
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
here is where it manages the controller where I entered the webview
class OpenSafariController: UIViewController, UIWebViewDelegate {
#IBOutlet weak var myWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func ritornaLista(_ sender: UIBarButtonItem) {
self.presentingViewController?.presentingViewController?.dismiss(animated: false, completion: nil)
}
}
delete the webview controller that is not needed. import SafariServices. here is the code to put on the button
#IBAction func apri(_ sender: UIBarButtonItem) {
let svc = SFSafariViewController(url: URL(string: self.link ?? "")!)
self.present(svc, animated: true, completion: nil)
}

Xib not showing up in view

I have a Xib file trying to set it up with my storyboard. Everything in the Xib file is fine, but for some reason, it's not showing. I imported a file from GitHub which is set to my Xib, it's in Objective-C and I set the bridging, no errors. But when I run it nothing shows its blank. Did I not set something in the View Controller? Everything is done programmatically and I just set the class in storyboard.
Screenshot of storyboard:
What the simulator gives me when I push to the ViewController:
This is what I'm supposed to see:
What I am trying to implement -
https://github.com/jberlana/JBCroppableView
My XIB class
import UIKit
class CropViewXIB: UIView {
#IBOutlet weak var ImageView: JBCroppableImageView!
#IBAction func SubAction(_ sender: Any) {
ImageView.removePoint()
}
#IBAction func AddAction(_ sender: Any) {
ImageView.addPoint()
}
#IBAction func UndoAction(_ sender: Any) {
ImageView.reverseCrop()
}
#IBAction func CropAction(_ sender: Any) {
ImageView.crop()
}
override init(frame: CGRect) {
super.init(frame: frame)
commomInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commomInit()
}
private func commomInit(){
Bundle.main.loadNibNamed("CropViewXIB", owner: self, options: nil)
self.addSubview(ImageView)
ImageView.frame = self.bounds
ImageView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
}
my view controller
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var cropView: CropViewXIB!
override func viewDidLoad() {
super.viewDidLoad()
}
}
The issue is that you didn't actually get the parent view for your UINib object.
Bundle.main.loadNibNamed("CropViewXIB", owner: self, options: nil)
The line above returns an [Any] in your case you aren't even using the view that it is returning. so the idea is to get the first object from it and cast it as UIView such as:
Bundle.main.loadNibNamed("CropViewXIB", owner: self, options: nil)?.first as? UIView
Personally this is how I interact with a Nib. I create a view property of type UIView that can be referred as the parent view for the nib, and all subviews get added to it instead of self.
Something like this:
final class SomeNibView: UIView {
public var view: UIView!
private func setup() { // called to the initializer
// grab the views from loadNibNamed
guard let _view = Bundle.main.loadNibNamed("name", owner: self, options: nil)?.first as? UIView else { return }
// set it to our view property
view = _view
// add this property to the nib subview aka self
addSubview(view)
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
private func addMulitpleSubviews() {
// instead of doing self.addSubview(....) when it comes to add other subviews
// you'll do this view.addSubview(....)
}
}
Try to load xib using programming not using storyboard.
override func viewDidLoad()
{
super.viewDidLoad()
guard let yourXIB = Bundle.main.loadNibNamed("CropViewXIB", owner: self, options: nil)?.first as? CropViewXIB else { return}
self.view.addSubview(yourXIB)
}

How to populate array and view it's data at the same time - Swift - IOS9

I am trying to retrieve data from an online database, and I do that successfully; However, after retrieving the data from the database I would like to store it in an array and then populate a listview and a mapview with it's data, but there is a problem, I am able to load the data and store it and view it, however the problem is that everytime the app loads no information appears until I go to another scene and go back, because I am populating the array though the AppDelegate. However, if I populate it through the viewdidload I get duplicate items in my table view.
Here is my code:
Approach number 1, which leads to duplicates
StoreViewController.swift
class StoreViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, StoresModelProtocoal {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
drawForm()
setUpMap()
self.hideKeyboardWhenTappedAround()
getCurrentLocation()
let hideStoreDetail: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.hideStoreDetails))
Map.addGestureRecognizer(hideStoreDetail)
//Create a nib for the custom cell and use it in the table
let nib = UINib(nibName: "CustomStoreCell", bundle: nil)
StoresListTable.registerNib(nib, forCellReuseIdentifier: "customStoreCell")
let storesModel = StoresModel()
storesModel.delegate = self
storesModel.downloadItems()
}
func itemsDownloaded(items: NSArray) {
print("Items downloaded")
for item in items
{
if let s = item as? Store
{
print(s.Address)
Globals.unsortedStoresList += [s]
Map.addAnnotation(s.Annotation)
do_table_refresh()
}
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Globals.unsortedStoresList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:CustomStoreCell = self.StoresListTable.dequeueReusableCellWithIdentifier("customStoreCell") as! CustomStoreCell
let s = Globals.unsortedStoresList[indexPath.row]
cell.loadItem(s.Name, StoreAddress: s.Address, StoreHoursOfOperation: s.HoursOfOperation, StoreDistanceFromCurrentLocation: String(s.DistanceFromCurrentLocation))
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//tableView.deselectRowAtIndexPath(indexPath, animated: true)
let s = Globals.unsortedStoresList[indexPath.row]
print(s.Name)
print(s.Address)
print(s.HoursOfOperation)
print(s.DistanceFromCurrentLocation)
//print("You selected cell #\(indexPath.row)!")
}
func do_table_refresh()
{
dispatch_async(dispatch_get_main_queue(), {
self.StoresListTable.reloadData()
return
})
}
I know this one duplicates the items because everytime the view is loaded it re-downloads all the data again; therefore, I tried looking for a better way and then I thought about doing the downloading process in my AppDelegate and then just write couple functions that take data from the array and display it, but the problem here is that the data would be displayed on the TableView right away without duplicates but it won't be displayed on the mapview at first run, instead I have to go to another scene and go back in order for the data to be displayed on the map.
Approach number 2
StoreViewController.swift
class StoreViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
drawForm()
setUpMap()
self.hideKeyboardWhenTappedAround()
getCurrentLocation()
let hideStoreDetail: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.hideStoreDetails))
Map.addGestureRecognizer(hideStoreDetail)
//Create a nib for the custom cell and use it in the table
let nib = UINib(nibName: "CustomStoreCell", bundle: nil)
StoresListTable.registerNib(nib, forCellReuseIdentifier: "customStoreCell")
loadMapAnnotations()
}
func loadMapAnnotations(){
for item in Globals.unsortedStoresList
{
Map.addAnnotation(item.Annotation)
do_table_refresh()
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Globals.unsortedStoresList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:CustomStoreCell = self.StoresListTable.dequeueReusableCellWithIdentifier("customStoreCell") as! CustomStoreCell
let s = Globals.unsortedStoresList[indexPath.row]
cell.loadItem(s.Name, StoreAddress: s.Address, StoreHoursOfOperation: s.HoursOfOperation, StoreDistanceFromCurrentLocation: String(s.DistanceFromCurrentLocation))
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//tableView.deselectRowAtIndexPath(indexPath, animated: true)
let s = Globals.unsortedStoresList[indexPath.row]
print(s.Name)
print(s.Address)
print(s.HoursOfOperation)
print(s.DistanceFromCurrentLocation)
//print("You selected cell #\(indexPath.row)!")
}
func do_table_refresh()
{
dispatch_async(dispatch_get_main_queue(), {
self.StoresListTable.reloadData()
return
})
}
AppDelegate.swift
class AppDelegate: UIResponder, UIApplicationDelegate, StoresModelProtocoal {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let storesModel = StoresModel()
storesModel.delegate = self
storesModel.downloadItems()
return true
}
//////////////////////////////////////
//Delegates
//////////////////////////////////////
func itemsDownloaded(items: NSArray) {
print("Items downloaded")
for item in items
{
if let s = item as? Store
{
print(s.Address)
Globals.unsortedStoresList += [s]
//Map.addAnnotation(s.Annotation)
}
}
}
Any help would be appreciated, Thanks in advance.
I was able to find a temporarily solution to the problem
I modified StoreViewController.swift to this, if anyone is having a similar problem.
class StoreViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, StoresModelProtocoal {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
drawForm()
setUpMap()
self.hideKeyboardWhenTappedAround()
getCurrentLocation()
let hideStoreDetail: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.hideStoreDetails))
Map.addGestureRecognizer(hideStoreDetail)
//Create a nib for the custom cell and use it in the table
let nib = UINib(nibName: "CustomStoreCell", bundle: nil)
StoresListTable.registerNib(nib, forCellReuseIdentifier: "customStoreCell")
Globals.unsortedStoresList.removeAll() //I added this line of code to remove the old list
let storesModel = StoresModel()
storesModel.delegate = self
storesModel.downloadItems()
}
func itemsDownloaded(items: NSArray) {
print("Items downloaded")
for item in items
{
if let s = item as? Store
{
print(s.Address)
Globals.unsortedStoresList += [s]
Map.addAnnotation(s.Annotation)
}
}
do_table_refresh()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Globals.unsortedStoresList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:CustomStoreCell = self.StoresListTable.dequeueReusableCellWithIdentifier("customStoreCell") as! CustomStoreCell
let s = Globals.unsortedStoresList[indexPath.row]
cell.loadItem(s.Name, StoreAddress: s.Address, StoreHoursOfOperation: s.HoursOfOperation, StoreDistanceFromCurrentLocation: String(s.DistanceFromCurrentLocation))
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//tableView.deselectRowAtIndexPath(indexPath, animated: true)
let s = Globals.unsortedStoresList[indexPath.row]
print(s.Name)
print(s.Address)
print(s.HoursOfOperation)
print(s.DistanceFromCurrentLocation)
//print("You selected cell #\(indexPath.row)!")
}
func do_table_refresh()
{
dispatch_async(dispatch_get_main_queue(), {
self.StoresListTable.reloadData()
return
})
}

Multiple ios push notification causes causes app to crash. Terminated due to signal 6(SIGABRT)

These are image's before and after the app crashes,the console only show message Message from debugger: Terminated due to signal 6 [[My app launches (when not running) successfully from push notification and also i get the desired screen and result, but crashes when it receive's notification again from tap of notification while the app is active. When the app is launched normally from home screen notification function and action work fine in both while is app active and in background.I am posting my code below please help me.
When I'm launching my application from the notification received, app lunches successfully and goto respected window,now again when i receive notification while app is open then app crashes, means whenever my app is not running in background or foreground and i launch my app using notification.. and then again when i receive notification app crashes
My Code is below please help
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.
let barAppearace = UIBarButtonItem.appearance()
barAppearace.setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics:UIBarMetrics.Default) //CODE TO REMOVETITLE OFACK BUTTON ITEM IN NAVIGATIION CONTROLLER
let notificationTypes : UIUserNotificationType = [.Alert, .Badge, .Sound]
let notificationSettings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
if let notification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject] {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AgentAllTab.readyNotificationAction), name: "AgentReadyNotification", object: nil)
let userInfo = launchOptions![UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject]
let aps = userInfo!["aps"] as! [String: AnyObject]
print("Remote noti data from didFinishLaunchingWithOptions \(aps)")
let data = aps["data"] as! [String: AnyObject]
let type = aps["type"] as! Int
print("notification TYPE \(type)")
switch type {
case 0 :
NSUserDefaults.standardUserDefaults().setObject(aps, forKey: "notificationlauch")
break
default:
break
}
return true
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings)
{
if notificationSettings.types != .None {
application.registerForRemoteNotifications()
}
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for i in 0..<deviceToken.length {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
NSUserDefaults.standardUserDefaults().setObject(tokenString, forKey: "DeviceToken")
NSUserDefaults.standardUserDefaults().synchronize()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print(error.localizedDescription)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
let aps = userInfo["aps"] as! [String: AnyObject]
let data = aps["data"] as! [String: AnyObject]
let type = aps["type"] as! Int
//Do something when app is active
if UIApplication.sharedApplication().applicationState == UIApplicationState.Active {
switch type {
case 0:
let custName = data["customerName"] as! String
let notification = CWStatusBarNotification()
notification.notificationStyle = .NavigationBarNotification
notification.notificationAnimationInStyle = .Top
notification.notificationLabelBackgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.8)
notification.notificationLabelTextColor = UIColor.whiteColor()
notification.notificationLabelFont = UIFont.boldSystemFontOfSize(15)
notification.displayNotificationWithMessage("\(custName) shorlisted you", forDuration: 3.0)
notification.notificationTappedClosure = {
NSNotificationCenter.defaultCenter().postNotificationName("AgentReadyNotification", object: self)
notification.dismissNotification()
}
break
default:
break
}
} else {
// Do something else when your app is in the background
switch type {
case 0 :
NSNotificationCenter.defaultCenter().postNotificationName("AgentReadyNotification", object: self)
break
default:
break
}
}
}
func applicationWillResignActive(application: UIApplication) {
print(" applicationWillResignActive")
}
func applicationDidEnterBackground(application: UIApplication) {
print(" applicationDidEnterBackgroundndddddddddddddd")
}
func applicationWillEnterForeground(application: UIApplication) {
print(" applicationWillEnterForeground")
}
func applicationDidBecomeActive(application: UIApplication) {
print(" applicationDidBecomeActive")
}
func applicationWillTerminate(application: UIApplication) {
print(" applicationWillTerminate")
}
}
//This code is from app delegate.swift
//Now code from the view controller where push is handled
import UIKit
class AgentAllTab: UITableViewController ,UIPopoverPresentationControllerDelegate ,AgentFilterDelegate {
var allQuoteId = String()
var filterTitle = "Market"
var quotes: [[String: AnyObject]] = [[:]] //VALUE FOR RESPONSE DICT
var newQuoteDict: Dictionary<String, String> = [String: String]() // DECLARING DICTIONARY FOR POST PARAMETERS
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AgentAllTab.readyNotificationAction), name: "AgentReadyNotification", object: nil)
if ( NSUserDefaults.standardUserDefaults().objectForKey("notificationlauch") != nil){
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AgentAllTab.readyNotificationAction), name: "NotificationLaunchReady", object: nil)
NSNotificationCenter.defaultCenter().postNotificationName("NotificationLaunchReady", object: self)
NSUserDefaults.standardUserDefaults().removeObjectForKey("notificationlauch")
NSUserDefaults.standardUserDefaults().synchronize()
return
}
executeFetch("/Market_all/")
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return quotes.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if filterTitle == "Ready"{
cell = tableView.dequeueReusableCellWithIdentifier("AgentAllTabReadyCell", forIndexPath: indexPath) as! AgentAllTabCellSubClass
if(quotes[indexPath.row].count == 0){
//normal code to hide all content of cell
}
}else{
//code in case we get data
}else{
//Code for other filter title same as above
}
return cell
}
func executeFetch(apiurl : String){
//function to fetch data from server and feed into uitableviewcontroller
}
//Function to handle the push notification
func readyNotificationAction(notification:NSNotification) {
filterTitle = "Ready"
self.tabBarController?.tabBar.hidden = true
executeFetch("/agentReady/")
}
}
Just one line of removal of code made things work perfectly, i was adding the observer in didFinishLaunchingWithOptions method.
My corrected code is below,
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let barAppearace = UIBarButtonItem.appearance()
barAppearace.setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics:UIBarMetrics.Default) //CODE TO REMOVETITLE OFACK BUTTON ITEM IN NAVIGATIION CONTROLLER
let notificationTypes : UIUserNotificationType = [.Alert, .Badge, .Sound]
let notificationSettings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
if let notification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject] {
//Removed this observer from here and placed it only where it was required
i.e.the desired viewcontroller
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AgentAllTab.readyNotificationAction), name: "AgentReadyNotification", object: nil)
// Also add deinit in the place where you place this observer and remove the observer from the viewcontroller so that observer is removed from notification center when app is terminated
let userInfo = launchOptions![UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject]
let aps = userInfo!["aps"] as! [String: AnyObject]
print("Remote noti data from didFinishLaunchingWithOptions \(aps)")
let data = aps["data"] as! [String: AnyObject]
let type = aps["type"] as! Int
print("notification TYPE \(type)")
switch type { case 0 :
NSUserDefaults.standardUserDefaults().setObject(aps, forKey: "notificationlauch")
break
default:
break
}
return true
}
//The rest of things remained same, Thank you #David V

I can't use touchesBegan/Moved/Ended and a UITapGestureRecognizer

Is it not possible to use both of these at the same time. Originally, I have overriden (Swift) touchesBegan/Moved/Ended in my ViewController.
Now, I'm wanting to add a TapGestureRecognizer to certain views under a certain situation, but the selector/action never gets fired.
class ViewController: UIViewController, UIGestureRecognizerDelegate {
...
func addTapGesturesOnNumberPadDisplay() {
if tapGestureRecognizerNumberPadView == nil {
tapGestureRecognizerNumberPadView = UITapGestureRecognizer(target: self, action: "handleTap:")
tapGestureRecognizerNumberPadView!.delegate = self
self.numberViewDone?.addGestureRecognizer(tapGestureRecognizerNumberPadView!)
}
}
...
func handleTap(sender: UITapGestureRecognizer) {
//never hit
Is this not possible? Should I just implement my own tapping ability in touchesBegan since I'm overriding it anyway, or is there a way to also use a tapGestureRecognizer here?
Since you have overriden touchesBegan/Moved/Ended in viewcontroller it should not have any impact on tap gestures in other subviews. Ideally it should work. Please check code below, works as expected.
class ViewController: UIViewController, UIGestureRecognizerDelegate {
#IBOutlet weak var categoryScrollView: UIScrollView!
var customView: UIView!
var tapGestureRecognizerNumberPadView : UITapGestureRecognizer?
override func viewDidLoad() {
super.viewDidLoad()
customView = UIView()
customView.frame.origin = CGPointMake(50,50)
customView.frame.size = CGSizeMake(100, 100)
customView.backgroundColor = UIColor.blueColor()
self.view.addSubview(customView)
addTapGesturesOnNumberPadDisplay()
}
func addTapGesturesOnNumberPadDisplay() {
if tapGestureRecognizerNumberPadView == nil {
tapGestureRecognizerNumberPadView = UITapGestureRecognizer(target: self, action: "handleTap:")
tapGestureRecognizerNumberPadView!.delegate = self
self.customView?.addGestureRecognizer(tapGestureRecognizerNumberPadView!)
}
}
func handleTap(sender: UITapGestureRecognizer) {
print("handleTap")
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
}
}
Please check is there any other gestures to 'numberViewDone' view.