My Protocol is not Calling - ios

I am using protocol for call method but my method does not call.Is there is any example which i use.
Here is my code:
ViewController
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
extension ViewController :ViewController1Delegate
{
func hello()
{
println("hbgyguyg");
}
}
In View Controller 1
import UIKit
#objc
protocol ViewController1Delegate
{
optional func hello()
}
class ViewController1: UIViewController {
var delegate: ViewController?
override func viewDidLoad() {
super.viewDidLoad()
delegate?.hello()
}
}
Please Help, I am new in Swift.Any help would be apperciated. Thanks in Advance

An example demo.
ViewController file
import UIKit
class ViewController: UIViewController, PopUpViewControllerDelegate
{
var popupVC: PopUpViewController!;
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view!.backgroundColor = UIColor.whiteColor();
self.popupVC = PopUpViewController();
self.popupVC.delegate = self;
self.showPopUpVC();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func popUpViewControllerDidPressOK(popUpVC: PopUpViewController) {
println("Yay?");
self.closePopUpVC();
}
func showPopUpVC()
{
let delayTime = dispatch_time(DISPATCH_TIME_NOW,
Int64(1.0 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
self .presentViewController(self.popupVC, animated: true, completion: nil);
}
}
func closePopUpVC()
{
let delayTime = dispatch_time(DISPATCH_TIME_NOW,
Int64(1.0 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
self.dismissViewControllerAnimated(true, completion: nil);
}
}
}
PopUpViewController file
import UIKit
protocol PopUpViewControllerDelegate
{
func popUpViewControllerDidPressOK(popUpVC: PopUpViewController);
}
class PopUpViewController: UIViewController {
var delegate: PopUpViewControllerDelegate!;
override func viewDidLoad() {
super.viewDidLoad()
self.view!.backgroundColor = UIColor.redColor();
// Do any additional setup after loading the view.
self.delegate!.popUpViewControllerDidPressOK(self);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Notice how in my ViewController viewDidLoad() method, I have a line that initialises the popUp view controller and then set its delegate to be the ViewController itself:
self.popupVC = PopUpViewController();
self.popupVC.delegate = self; // you're missing this line I believe ?
I don't use Interface Builder or Storyboard but maybe select your VC1 in your Storyboard and look in the connections inspector to see if you drag a line from "delegate" to your ViewController file owner thing.
In the end, you should see a red screen popup after 1 second, followed by the word "Yay?" logged into your Xcode console and finally the popupVC dismisses.

Related

(Update) UITapGestureRecognizer Action is not called when using UIApplication

I thought that I have solved the following error with inheriting from NSObject. The frustrating thing is that id did work once :-)
The beneth code should run(not wok) in any ViewController.
The problem is that the action(tapped) is not called: Can you see why not?
import Foundation
import UIKit
public class TestErrorClass: NSObject {
var errorView: UIView?
public override init() {}
public func showErrorMessage(errorMessage: String) {
let APPDELEGATE = UIApplication.shared.delegate as UIApplicationDelegate?
if let window = APPDELEGATE?.window{
let v = window?.subviews[0]
self.errorView = UIView(frame: (v?.frame)!)
self.errorView?.backgroundColor = UIColor.red
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
tapGesture.isEnabled = true
errorView!.addGestureRecognizer(tapGesture)
v?.addSubview(self.errorView!)
}
}
#objc func tapped(_ sender: UITapGestureRecognizer) {
errorView!.removeFromSuperview()
}
}
Used in this code:
import UIKit
class NetKitSampleAppViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidLayoutSubviews() {
let b = TestErrorClass()
b.showErrorMessage(errorMessage: "Bla bal")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Screen transition cannot be done

I wanna transition screens in my app but it cannot be done.
I used TabBarController and I made Tab1 item and Tab2 item.
When I tapped Tab2 in my simulator, my app dropped.
import UIKit
import SwiftyJSON
class ViewController: UIViewController {
#IBOutlet var KenshinPic: UITabBarItem!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController : UITabBarControllerDelegate {
public func tabBarController(tabBarController: UITabBarController, viewController: UIViewController) -> Bool {
if(viewController.restorationIdentifier == "first") {
self.tabBarController!.setViewControllers([KenshinSendController() , KenshinViewController()], animated: false);
let items = self.tabBarController!.tabBar.items;
items![1].title = "Second";
items![0].title = "First";
return false;
}
return true;
}
}
Below sentences didn't be called in Xcode when I run my app.
enter code here
self.tabBarController!.setViewControllers([KenshinSendController() , KenshinViewController()], animated: false);
Error message was 'signal SIGABRT'
in class AppDelegate: UIResponder, UIApplicationDelegate {
of AppDelegate file.
What shoud I do?

Swift3.0 I want to get object of AppDelegate

I wanna get object of AppDelegate.
This program can build but it will stop running with lldb error.
Maybe the problem is the dirrerence of Swift2.0 and 3.0.
My textbook is for swift2.0 but I am using xcode8.0 and Swift3.0.
Error is here.
let ap = UIApplication.shared.delegate as! AppDelegate
I used this page for fixing.
How do I get a reference to the app delegate in Swift?
import UIKit
class FirstViewController: UIViewController {
#IBOutlet weak var dataTextField: UITextField!
let ap = UIApplication.shared.delegate as! AppDelegate
override func viewWillAppear(_ animated: Bool) {
dataTextField.text = String(ap.cmValue)
}
#IBAction func tapInpu() {
dataTextField.resignFirstResponder()
if let text = dataTextField.text{
if let cmValue = Double(text){
ap.cmValue = cmValue
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
If you remove ap initialization and ap.cmValue = cmValue, does it works ?
If it does work check your outlet referencing in your storyboard you may have old non existent references

Looking understand why delegate keep alive

I have the following structure
Main ViewController: it is responsible to call the (A) view controller.
(A) ViewController: create an CustomClass instance and has a delegate for this class.
CustomClass: in each period of 1 second, a message is sent to (A) view controller via delegate.
Until here all works fine. Once I returned to Main ViewController the delegate keep alive, in other words, the delegate updates A(ViewController) variable. I checked that viewDidDisappear of (A) ViewController is called.
When I return again from Main ViewController to (A) ViewController, a new variable instance is created. I don't understand this anyway.
Besides this doubt, I would like to understand why the delegate keep alive when I return to main view controller. I am using a UINavigationItem to navigation.
I am a beginner in IOS development.
Thanks advanced!!!
Edit 1:
The (A)ViewController is called from MainViewController by Segue. The segue was added via storyboard.
MainViewController.swift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
AViewController.swift
class ScanDevices : UIViewController, CustomClassDelegate {
var myInts : [Int] = []
var customClass : CustomClass!
override func viewDidLoad() {
super.viewDidLoad()
print("viewDidLoad")
if customClass == nil {
customClass = CustomClass()
customClass.customClassDelegate = self
}
}
override func viewWillAppear(animated: Bool) {
print("viewWillAppear")
}
override func viewDidAppear(animated: Bool) {
print("viewDidAppear")
}
override func viewWillDisappear(animated: Bool) {
print("viewWillDisappear")
}
override func viewDidDisappear(animated: Bool) {
print("viewDidDisappear")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func didDiscoverPeripheralInt(peripheral: Int) {
myInts.append(peripheral)
print("Number = \(myInts.count)")
}
}
CustomClass.swift
class CustomClass : NSObject {
var customClassDelegate : CustomClassDelegate?
// MARK: init
override init() {
super.init()
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "writeInt", userInfo: nil, repeats: true)
}
func writeInt () {
CustomClassDelegate?.didDiscoverPeripheralInt(3)
}
}
var customClassDelegate : CustomClassDelegate?
You are holding a string reference to your delegate.
It needs to be
weak var customClassDelegate : CustomClassDelegate?
Take a look at the following document :
http://krakendev.io/blog/weak-and-unowned-references-in-swift
Your CustomClass holds strong reference to the delegate. You have to mark the property with weak:
weak var customClassDelegate : CustomClassDelegate?

Delegate Not Called In SWIFT iOS

I am Created 2 Views, One is and Used Protocol and Delegate. For first view the Delegate function is not called.
My FirstView Controller : Here I am Accessing the Delegate Function.
import UIKit
class NextViewController: UIViewController,DurationSelectDelegate {
//var secondController: DurationDel?
var secondController: DurationDel = DurationDel()
#IBAction func Next(sender : AnyObject)
{
let nextViewController = DurationDel(nibName: "DurationDel", bundle: nil)
self.navigationController.pushViewController(nextViewController, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
secondController.delegate=self
}
func DurationSelected() {
println("SUCCESS")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
My SecondView Controller : Here I Am creating Delegate.
import UIKit
protocol DurationSelectDelegate {
func DurationSelected()
}
class DurationDel: UIViewController {
var delegate: DurationSelectDelegate?
#IBAction func Previous(sender : AnyObject) {
//let game = DurationSelectDelegate()
delegate?.DurationSelected()
self.navigationController.popViewControllerAnimated(true)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
To me, it looks like you're pushing a view controller that you haven't actually set the delegate for. If you change your "Next" function, to include the line
nextViewController.delegate = self
You should see that the delegation works. In doing this, you can also probably remove the creation of "secondController", as it looks like that's redundant.
The naming convention you have followed would confuse fellow developers in your team. The instance should have been
let durationDel = DurationDel(nibName: "DurationDel", bundle: nil)
And then as #Eagerod mentioned, the delegate you would set is
durationDel.delegate = self

Resources