0

I have a OnePresence.swift file and on it I have:

extension OnePresence: XMPPStreamDelegate {
    public func xmppStream(sender: XMPPStream, didReceivePresence presence: XMPPPresence) {
        OpenChatsTableViewController().showAlert(username)
    }
}

In my OpenChatsTableViewController:

func showAlert(username: String) {
    showBuddyRequest(username)
}

And where:

import Foundation

protocol BuddyRequestProtocol {
    func showBuddyRequest(fromUser: String)
}

extension BuddyRequestProtocol where Self: UIViewController {
    func showBuddyRequest(fromUser: String) {
        let alert = UIAlertController(title: "AAA", message: "\(fromUser) wants to add you as a friend.", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Friend Request", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }
}

in this case I get the next error:

Warning: Attempt to present <UIAlertController: 0x7c3c4400> on <OpenChatsTableViewController: 0x7b0ecee0> whose view is not in the window hierarchy!

How can I fix this code and rewrite/refactor it?

Orkhan Alizade
  • 7,379
  • 14
  • 40
  • 79

1 Answers1

-1

Your OpenChatsTableViewController is not shown, so it cannot present the alert. You first have to make sure the OpenChatsTableViewController is in view (eg by pushing it on the navigation stack) before trying to show the alert.

TheEye
  • 9,280
  • 2
  • 42
  • 58
  • Apparently you make a new one (see the brackets "()") - you have to take the one you are showing – TheEye Dec 10 '15 at 12:50
  • So, how need I use it? Can you help me with it? When I try without brackets it gives me error – Orkhan Alizade Dec 10 '15 at 13:06
  • Of course, it's the CLASS you are using, not the instance. Somewhere you create the `OpenChatsTableViewController` when you show it - you have to keep a reference to that instance, and use that one for displaying your alert. If you don't know what I'm talking about, please read up on classes and instances (eg here: http://stackoverflow.com/questions/1053592/what-is-the-difference-between-class-and-instance-methods) – TheEye Dec 10 '15 at 13:11
  • I tried this: `var a = OpenChatsTableViewController()` before the class I defined it, later I tried to use: `a.showAlert()` but it shows that OpenChats doesn't have such method – Orkhan Alizade Dec 10 '15 at 13:19
  • Okay, I fixed this error, too, but it still returns me hierarchy error – Orkhan Alizade Dec 10 '15 at 13:34