Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ifaddrs in Swift Framework

Tags:

swift

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?

like image 715
Asyra Avatar asked Sep 12 '14 12:09

Asyra


1 Answers

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

like image 129
David Robles Avatar answered Nov 03 '22 14:11

David Robles