delegate in swift 3 does not perform view related codes - ios

In my project I have some delegates that works fine with returning data but I want to add some subview or do any anything in the delegate method on the receiving end nothing happen but the other codes that are in the same method are OK!
My other question is also realated to delegates :
This happens for some delegates. The delegate does not respond but I found a very strange fix on the web and I need to know why this happens and why this fix works!
My First View :
protocol SomeDelegate {
func someMethod()
}
class FirstViewClass {
//in init or didLoad method
var delegate: SomeDelegate?
// THIS DELEGATE WON'T WORK BUT WHEN I ADD THIS LINE IT WORKS FINE( IT STILL HAS THE ABOVE PROBLEM)
self.delegate = SecondViewClass()
//in some custom method
self.delegate?.someMethod();
}
My Second View:
class SecondViewClass : SomeDelegate {
var firstView = FirstViewClass()
// this is in init or didLoad method
firstView.delegate = self
//this is in some custom method
someMethod()
}

A simple working prototype:
protocol SomeDelegate {
func someMethod()
}
class FirstViewClass {
var delegate: SomeDelegate?
}
class SecondViewClass : SomeDelegate {
var firstView = FirstViewClass()
func someMethod() {
print("called via delegate")
}
}
var firstClass = FirstViewClass()
var secondClass = SecondViewClass()
firstClass.delegate = secondClass
firstClass.delegate?.someMethod()

Related

Calling delegate methods from extension throws nill, but works on action event

Below is the code snippet, delegate never calls when XMPPStreamDelegate methods called periodically. Presence service delegate throws nil inside of extension but gives value when calling some action from another view controller.
public protocol PresenceServiceDelegate{
func didPresenceReceive()
}
class PresenceService: NSObject{
var delegate: PresenceServiceDelegate?
public override init()
delegate = self
}
}
extension PresenceService: XMPPStreamDelegate {
public func didReceive presence() // XMPPStrem delegate
// My Presence Service delegate not at all calling (delegate throws nil )
delegate?.didPresenceReceive()
}
}
class ViewController: UIViewController{
var presence = PresenceService()
func viewDidLoad() {
presence.delegate = self
}
}
extension ViewController: PresenceServiceDelegate {
public func didPresenceReceive(){
print("test")
}
}
The Below code works fine as expected. During XMPPStreamDelegate calls presenceservice delegate object throws nill and not recognised, here the below code calling instance of presenceservice's class which enabling it's own delegate instance and triggered value to the view controller as expected.
class PresenceService: NSObject{
var delegate: PresenceServiceDelegate?
public override init()
delegate = self
}
// Singleton instance
public class var sharedInstance : PresenceService {
struct PresenceServiceInstance {
static let instance = PresenceService()
}
return PresenceServiceInstance.instance
}
}
extension PresenceService: XMPPStreamDelegate {
public func didReceive presence() // XMPPStrem delegate
// My Presence Service delegate not at all calling (delegate throws nil )
PresenceServiceInstance.sharedInstance.delegate?.didPresenceReceive()
}
}

Weak delegate becomes nil

In my app I'm using delegates, so that I can read the data when ever it's ready.
I'm calling a delegate from two classes. Here is my code
protocol MyDelegate: class {
func getData()
}
class MyDelegateCalss {
weak var delegate: MyDelegate?
func loadData() {
// doing some actions
if(self.delegate != nil){
self.delegate!.getData!()
}
}
}
In one class I'm loading this method in tableview numberOfSections delegate method.
class A: UIViewController, MyDelegate {
func somefunc(){
let mydelegatecls : MyDelegateCalss = MyDelegateCalss()
mydelegatecls.delegate = self
mydelegatecls.loadData()
}
func getData(){
// Doing some actions
}
}
This method I'm loading from another calss.
class B: UIViewController, MyDelegate {
open func testfunc(){
let mydelegatecls : MyDelegateCalss = MyDelegateCalss()
mydelegatecls.delegate = self
mydelegatecls.loadData()
}
func getData(){
// doing some other stuff
}
}
class C: UIViewController {
func testfunc(){
let b : B = B()
b.testfunc()
}
}
Here from class A my delegate is working fine. and I'm able to see getData method is calling .
from Class B, the delegate becomes nil and unable to see getData method is called
If I make the delegate reference its working fine. But that will cause memory leak.
How can handle this case ?
Your delegate var is declared as weak. If nothing keep a strong reference on the object you assign as the delegate (implementing MyDelegate), your delegate will pass to nil as soon as the object is released (eg. the end of the scope where you instantiate it).
Some good read: https://cocoacasts.com/how-to-break-a-strong-reference-cycle/

Call view controller method from custom class

I have a custom class and a view controller.
My custom class:
class ChatManager:NSObject {
func messageArrived() {
//When Message arrives I am handling it from here
//I need something like that: Viewcontroller.updateTable()
}
}
When message arrives from internet I need to update tableview in view controller. So I mean I have to call a view controller method from messageArrived method. How can I do this ?
Here is a simple example of using delegate:
declare the delegate before your chat manager class
protocol ChatManagerDelegate {
func manageMessage()
}
when the message arrived, call the delegate method to handle it.
class ChatManager: NSObject {
var delegate: ChatManagerDelegate?
func messageArrived() {
self.delegate!.manageMessage()
}
}
in your view controller, remember to set the delegate of the chat manager to self.
class ViewController: ChatManagerDelegate {
var manager = ChatManager()
manager.delegate = self
func manageMessage() {
self.updateTable()
}
}
This would be a possible implementation:
ViewController:
class ViewController: UIViewController,ChatManagerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let myChatManager = ChatManager()
myChatManager.delegate = self
}
func messageDidArrive() {
// Do Things here.
}
}
Chatmanager:
class ChatManager:NSObject {
var delegate:ChatManagerDelegate?
func messageArrived() {
//When Message arrives I am handling it from here
//I need something like that: Viewcontroller.updateTable()
}
}
Delegate-Protocol:
protocol ChatManagerDelegate{
func messageDidArrive()
}

Why custom delegate in iOS is not called

I am trying to create a custom delegate using playground in swift. However the doSomething method is not being called through callback.
It seems that delegate?.doSomething() does not fire to the XYZ class doSomething method.
Thanks in advance!
import UIKit
#objc protocol RequestDelegate
{
func doSomething();
optional func requestPrinting(item : String,id : Int)
}
class ABC
{
var delegate : RequestDelegate?
func executerequest() {
delegate?.doSomething()
println("ok delegate method will be calling")
}
}
class XYZ : RequestDelegate
{
init()
{
var a = ABC()
a.delegate = self
}
func doSomething() {
println("this is the protocol method")
}
}
var a = ABC()
a.executerequest()
It seems that delegate?.doSomething() does not fire to the XYZ class
doSomething method.
That is correct. class ABC has an optional delegate property, but the value of
the property is nowhere set. So the delegate is nil
and therefore the optional chaining
delegate?.doSomething()
simply does nothing. Also you have defined a class XYZ but
not created any instances of that class.
If you set the delegate of a to an instance of XYZ then
it will work as expected:
var a = ABC()
a.delegate = XYZ()
a.executerequest()

Does the implementation of GPPSignInDelegate have to be a ViewController or AppDelegate?

I'm trying to integrate an iOS application that I'm writing in Swift with Google Plus following the instructions here. After getting it all to work within a ViewController I foolishly thought I could encapsulate the authentication behaviour inside its own class (below)
The problem is that the two GPPSignInDelegate protocol functions finishedwithAuth and didDisconnectWithError never get called. If I pass in a ViewController or the AppDelegate that implements GPPSignInDelegate and assign it to the googlePlus.delegate the callbacks are called successfully; when I assign self to the delegate the callbacks are never called.
import Foundation
class GoogleAuthentication : GPPSignInDelegate {
let kClientId: NSString = ""
let googlePlus: GPPSignIn
var authenticatedSuccessfully: Bool?
// Passing in a ViewController implementing GPPSignInDelegate works
// init(delegate: GPPSignInDelegate) {
init() {
self.delegate = delegate
googlePlus = GPPSignIn.sharedInstance()
googlePlus.shouldFetchGooglePlusUser = true
googlePlus.clientID = kClientId
googlePlus.scopes = [kGTLAuthScopePlusLogin]
googlePlus.delegate = self // works when assignging delegate passed in
authenticatedSuccessfully = googlePlus.trySilentAuthentication()
}
func authenticate() {
googlePlus.authenticate()
}
func finishedWithAuth(auth: GTMOAuth2Authentication!, error: NSError!) {
println("finished with auth!")
}
func didDisconnectWithError(error: NSError!) {
println("disconnected with error!")
}
}
Is there something I'm missing or does the GPPSignInDelegate have to be implemented by a ViewController or the AppDelegate? And if so, why?
The delegate object has to inherit from NSObject. So it becomes:
class GoogleAuthentication: NSObject, GPPSignInDelegate {

Resources