Syntax "Selector" Swift 2.2 - swift

I'm trying to fix my NSNotificationCenter and its not working
the message :
'Use of string literal for Objective-C selectors is deprecated; use '#selector' instead'.
the line :
NSNotificationCenter.defaultCenter().addObserver(self, Selector :#selector(GameViewController.goBack)(GameViewController.goBack), object: nil)
self.dismissViewControllerAnimated(true, completion: {
});
}

#Eendje's answer is incorrect by its first comment.
I think it is better answer.
NSNotificationCenter.defaultCenter().addObserver(self, #selector(self.goBack), name: "your notification name", object: nil)
If some actions has target, it should be presented like #selector(target.method) or #selector(target.method(_:))
Here is another example
UIGestureRecognizer(target: target action:#selector(target.handleGesture(_:))

The code you pasted doesn't make any sense:
Selector :#selector(GameViewController.goBack)(GameViewController.goBack) // ???
It should be:
NSNotificationCenter.defaultCenter().addObserver(self, #selector(goBack), name: "your notification name", object: nil)

You have to look at this: https://github.com/apple/swift-evolution/blob/master/proposals/0022-objc-selectors.md
The #selector proposal was made in conjunction with another proposal, specifying swift functions by their argument labels. So if I have a struct:
struct Thing
func doThis(this: Int, withOtherThing otherThing: Int) {
}
}
I would reference that function like:
let thing = Thing()
thing.doThis(_:withOtherThing:)
Remember here I'm referencing the function itself, not calling it.
You would use that with #selector:
#selector(self.doThis(_:withOtherThing:)
Function with no arguments:
#selector(self.myFunction)
Function with one implicit argument:
#selector(self.myOtherFunction(_:))

Yes, in Swift 2.2 the string literals for selectors is deprecated, and instead there this new operator #selector that you need to be using.
Refer this proposal of #selector with good examples here:
https://github.com/apple/swift-evolution/blob/master/proposals/0022-objc-selectors.md

Add #objc to your selector method:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "YOUR_SELECTOR_METHOD:", name: "your notification name", object: nil)
#objc func YOUR_SELECTOR_METHOD(notification: NSNotification) {
//your code
}

Related

SwiftUI - KV Observe completion from Combine does not get triggered

I am trying to build a VOIP app using lib called VailerSIPLib. As the library was built using Obj-C and heavily using NotificationCenter to to publish the changes the active states all over the place.
I currently at the CallView part of the project, I can manage to start, end, reject calls. However, I need to implement connectionStatus in the view which will give information about the call like duration, "connecting..", "disconnected", "ringing" etc.
The below code is all in CallViewModel: ObservableObject;
Variables:
var activeCall: VSLCall!
#Published var connectionStatus: String = ""
Initializer:
override init(){
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(self.listen(_:)), name: Notification.Name.VSLCallStateChanged, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.buildCallView(_:)), name: Notification.Name.CallKitProviderDelegateInboundCallAccepted, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.buildCallView(_:)), name: Notification.Name.CallKitProviderDelegateOutboundCallStarted, object: nil)
}
Methods:
func setCall(_ call: VSLCall) {
self.activeCall = call
self.activeCall.observe(\.callStateText) { (asd, change) in
print("observing")
print("\(String(describing: change.oldValue)) to \(String(describing: change.newValue)) for \(call.callId)")
}
}
#objc func listen(_ notification: Notification) {
if let _ = self.activeCall {
print(self.activeCall.callStateText)
}
}
#objc func buildCallView(_ notification: Notification) {
print("inbound call")
self.isOnCall = true
}
Problem:
It prints out every thing except the completionBlock in setCall(_:). listen(_:) function validates that the state of the activeCall is changing and I would want to use that directly, however it does not work correct all the time. It should be triggered when the call is answered with callState value of .confirmed but sometime it does. This how I will know that it is time start the timer.
Other point is, in the example project of the VialerSIPLib they used self.activeCall.addObserver(_:) and it works fine. The problem for that is it throws a runtime error at the method something like didObservedValueChange(_:) and logs An -observeValueForKeyPath:ofObject:change:context: message was received but not handled.
Finally there is yellow warning at the activeCall.observe(_:) says
Result of call to 'observe(_:options:changeHandler:)' is unused
which I could not find anything related to it.
Finally there is yellow warning at the activeCall.observe(_:) says
Result of call to 'observe(_:options:changeHandler:)'
This is telling you what the problem is. The observe(_:options:changeHandler:) method is only incompletely documented. It returns an object of type NSKeyValueObservation which represents your registration as a key-value observer. You need to save this object, because when the NSKeyValueObservation is destroyed, it unregisters you. So you need to add a property to CallViewModel to store it:
class CallViewModel: ObservableObject {
private var callStateTextObservation: NSKeyValueObservation?
...
And then you need to store the observation:
func setCall(_ call: VSLCall) {
activeCall = call
callStateTextObservation = activeCall.observe(\.callStateText) { _, change in
print("observing")
print("\(String(describing: change.oldValue)) to \(String(describing: change.newValue)) for \(call.callId)")
}
}
You could choose to use the Combine API for KVO instead, although it is even less documented than the Foundation API. You get a Publisher whose output is each new value of the observed property. It works like this:
class CallViewModel: ObservableObject {
private var callStateTextTicket: AnyCancellable?
...
func setCall(_ call: VSLCall) {
activeCall = call
callStateTextTicket = self.activeCall.publisher(for: \.callStateText, options: [])
.sink { print("callId: \(call.callId), callStateText: \($0)") }
}
There's no specific reason to use the Combine API in your sample code, but in general a Publisher is more flexible than an NSKeyValueObservation because Combine provides so many ways to operate on Publishers.
Your error with addObserver(_:forKeyPath:options:context:) happens because that is a much older API. It was added to NSObject long before Swift was invented. In fact, it was added before Objective-C even had blocks (closures). When you use that method, all notifications are sent to the observeValue(forKeyPath:of:change:context:) method of the observer. If you don't implement the observeValue method, the default implementation in NSObject receives the notification and raises an exception.

Why aren't default parameters for functions respected when called via Selector in Swift?

Methods called via Selector don't respect default parameter values.
EXAMPLE
If I have a button wired up to call a function via a selector:
func setupButton() {
self.button.addTarget(self, action: #selector(printValue), for: .touchUpInside)
}
#objc func printValue(value:Int = 7)
{
if value == 7 {
print("received default")
} else {
print("default unused")
}
}
When calling this method via code "received default" is printed, but when I press the button and call the method via selector "default unused" is printed because 7 wasn't set as the value.
Why is this happening?
Default parameters are inserted by the Swift compiler when you call the function.
So this is a compile-time thing.
When manually calling the function via a selector, you use the Objective-C runtime, which has no idea about your default parameters.
This is a runtime thing.
Moreover, default parameters don't exist in Objective-C.
You can think of Swift default parameters as a compile-time convenience.
But once you run your code, they're basically gone.
EDIT
If you're looking for a workaround, I can suggest having two different functions, without using default parameters:
#objc func printValue()
{
printValue(value: 7)
}
#objc func printValue(value:Int)
{}
This way, you can call it without arguments through the Objective-C runtime.
Note that when using #selector, you'll need to cast to resolve ambiguity:
self.button?.addTarget(self, action: #selector((printValue as () -> Void)), for: .touchUpInside)

Ambiguous reference when using selectors

Ready to use example to test in Playgrounds:
import Foundation
class Demo {
let selector = #selector(someFunc(_:))
func someFunc(_ word: String) {
// Do something
}
func someFunc(_ number: Int) {
// Do something
}
}
I'm getting an Ambiguous use of 'someFunc' error.
I have tried this answer and getting something like:
let selector = #selector(someFunc(_:) as (String) -> Void)
But still getting the same result.
Any hints on how to solve this?
Short answer: it can't be done.
Long explanation: when you want to use a #selector, the methods need to be exposed to Objective-C, so your code becomes:
#objc func someFunc(_ word: String) {
// Do something
}
#objc func someFunc(_ number: Int) {
// Do something
}
Thanks to the #objc annotation, they are now exposed to Objective-C and an compatible thunk is generated. Objective-C can use it to call the Swift methods.
In Objective-C we don't call a method directly but instead we try to send a message using objc_msgSend: the compiler is not able to understand that those method are different, since the generated signature is the same, so it won't compile. You will face the error:
Method 'someFunc' with Objective-C selector 'someFunc:' conflicts with previous declaration with the same Objective-C selector.
The only way to fix it is to have different signatures, changing one or both of them.
The selector is obviously ambiguous, neither methods have external parameter names. Remove the empty external parameters to solve this:
#objc func someFunc(word: String) {
// Do something
}
#objc func someFunc(number: Int) {
// Do something
}
After that, you should specify a selector with the parameter name:
#selector(someFunc(word:))
or
#selector(someFunc(number:))

Swift: Creating a function and calling it multiple times?

I am very new to Swift and I can't find an answer to my qustion.
I am working on an app that will do a lot of the same functions but on separate button pushes. I could reduce my code and time updating greatly if I am able to write a function or action and just call it by name on a button push.
Does Swift have a way to do something like this:
Func doMath {
var answer = 1+1
var answer2 = 2+2
}
Func buttonPush {
call doMath
}
What you need is an IBAction. Using the Assistant view hold the control key and drag it into your code. Then change the connection type to Action and give it a useful name.
From inside your IBAction you can do any maths or call any maths function you need. Using functions to minimise code duplication is a good idea.
Here's an example of an Action that starts a timer.
#IBAction func play(sender: AnyObject) {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)
}
I sugguest you do some examples that use IBAction.
I liked the Ray Wenderlich ones myself.
Here is some code for creating a function that takes two integer parameters. It's taken from the Apple developer documentation.
apple docs hopefully that's what you need.
func halfOpenRangeLength(start: Int, end: Int) -> Int {
return end - start
}

Alternate way (using Selector) to set up notification observer

I have successfully setup notification observer using the code below:
func setupNotification {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "action:", name: notificationString, object: nil)
}
func action(notification: NSNotification) {
// Do something when receiving notification
}
However, I am not interested in the coding style above since there might be a chance that I could type or copy/paste wrong method name action:.
So I tried to addObserver in a different way: NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector(/* What to pass in here??? */), name: notificationString, object: nil), I don't know what to pass in selector: Selector(...).
XCode hints me: Selector(action(notification: NSNotification), but this is illegal.
In Objective C, I can easily pick up a method at this phase but I don't know how in Swift.
Have you tried this syntax? Let me know.
Thanks,
The syntax for a Selector is Selector("action:")
Not the direct answer for your question but I have an idea.
In swift instance methods are curried functions that take instance as first argument. Suppose you have a class like this.
class Foo: NSObject {
func bar(notification: NSNotification) {
// do something with notification
}
}
And somewhere in code you have an instance of Foo.
let foo = Foo()
Now you can get bar method as a variable like this
let barFunc = Foo.bar(foo)
Now imagine in the future NSNotificationCenter has an api that lets you assign functions to it instead of selectors.
NSNotificationCenter.defaultCenter().addObserverFunction(barFunc, name: "notificationName", object: nil)
Though I don't like to use NSNotificationCenter but It would be nice to see this kind of api in the future.