Swift: How do you use an Objective-C function from a linked library?
Background
I'm new to iOS development and playing with Swift for the sake of learning. As a small task, I'm trying to get the SSID of the network the device is currently connected to.
This is a well covered land on the stack using Objective-C: iPhone get SSID without private library for example ... but Objective-C / Swift dance causes some conceptual problems.
Specifically, the proposed solution (discussed in the above post) is to call a function CNCopyCurrentNetworkInfo()
- but according to Apple documentation , this function is not available in Swift.
Until
I have included (I think correctly) SystemConfiguration.framework
by adding it to the Related Structures and Libraries of the project. I also brought it into view controller with import SystemConfiguration
.
Questions
- Should I also use it
import SystemConfiguration
, or is it already done due to the inclusion of the framework with my project? -
Is there any other / better way to include the library
SystemConfiguration
? -
Big . After importing the required library, how do you call the Objective-C function from the library?
Thank!
source to share
Apple Interoperability Book (from Understanding the Quick Import Process ):
Any Objective-C framework (or C library) available as a module can be imported directly into Swift. This includes all Objective-C system frameworks such as Foundation, UIKit, and SpriteKit, as well as the common C libraries that come with the system.
Regarding your specific questions:
-
The opposite case: you don't need to manually enable Apple frameworks. Xcode will automatically make them available to you if you have a valid operator
import
(for exampleimport SystemConfiguration
in your case), even - or rather: especially - in the playground! -
same...
-
Given the above import statement is
SystemConfiguration
indeed imported, since you can call its functions (for exampleSCCopyLastError() // --> __NSCFError
) and access its constants (for examplekCFErrorDomainSystemConfiguration // --> com.apple.SystemConfiguration
). UnfortunatelyCaptiveNetwork
it doesn't seem to be imported with it (for exampleCNCopySupportedInterfaces() // --> Use of unresolved identifier
).
However, you should use this structure on the Objective C side and just call your own wrapper functions from Swift. You just need to remember to include them in the import list given in your bridge header (see Swift and Objective-C in the same project for more on bridging headers).
source to share
I know this does not directly answer your question, but it does answer your problem. In your case, you can do everything quickly.
After importing the library
import SystemConfiguration.CaptiveNetwork
You can immediately call:
CNCopySupportedInterfaces()
and it will work. Confirmed in Xcode 6.3.2.
source to share