Since frameworks do not support bridging headers, how do I import ifaddrs.h
into a swift file inside a framework?
Or is there another way to get the devices ip address on the LAN, that will work on both iOS and OS X?
In an app target, a bridging header does the trick. Inside a framework target, things are trickier. Inside Swift code we can only import so called modules. The trick is to define a module map that provides the desired C library resource and make it visible by setting SWIFT_INCLUDE_PATHS inside the build settings (Build Settings->Swift Compiler->Import Paths) to the path of the module map file. There are two methods for doing this:
1) The following allows for a pure swift implementation by exposing the ifaddrs.h interface directly but sadly requires an exact path to the header file, which is not desirable if you're ever going to release your library as open source.
module.modulemap
module ifaddrs [system] {
header
"/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/ifaddrs.h"
export *
}
Add to swift code
import ifaddrs
2) The second way is to create an Objective-C class which provides an interface to ifaddrs.h but hides the actual import of ifaddrs.h the source *.m file.
NetworkTools.h
@interface NetworkTools : NSObject
+ (NSDictionary *)getIFAddresses;
@end
NetworkTools.m
#import "NetworkTools.h"
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netdb.h>
@implementation NetworkTools
+ (NSDictionary *)getIFAddresses {
NSDictionary *addresses;
// code
return addresses;
}
module.modulemap
module NetworkTools {
header "Obj-C Tools/NetworkTools.h"
export *
}
Add to swift code
import NetworkTools
For more info on how this all works together, check out:
Sample project on Github: https://github.com/danieleggert/mixed-swift-objc-framework
As well as the article about Clang modules: http://clang.llvm.org/docs/Modules.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With