在设计iOS网络开发中,我们需要获取本机的IP地址,那么通过Swift调用OC如何来实现呢?我将会通过一个Swift的iOS项目,然后通过调用OC的方法,来实现这个功能。
(1)在Swift项目中新建Cocoa Touch Class,语言选择Objective-C,然后自动会提示新建一个Swift和OC的桥接文件,选择Yes就好。然后就会自动生成一个 “项目名-Bridging-Header.h”的文件。我新建的OC文件名是GetIPAddress.
(2)然后在桥接文件中加入OC的头文件:
#import "GetIPAddress.h"
(3)然后在OC头文件GetIPAddress.h中实现如下:
#import <Foundation/Foundation.h> @interface GetIPAddress : NSObject + (NSString *)deviceIPAdress; @end
// // GetIPAddress.m // AlertDialogDemo // // Created by chenyufeng on 15/9/8. // Copyright (c) 2015年 chenyufengweb. All rights reserved. // #import "GetIPAddress.h" #include <ifaddrs.h> #include <arpa/inet.h> @implementation GetIPAddress + (NSString *)deviceIPAdress { NSString *address = @"an error occurred when obtaining ip address"; struct ifaddrs *interfaces = NULL; struct ifaddrs *temp_addr = NULL; int success = 0; success = getifaddrs(&interfaces); if (success == 0) { // 0 表示获取成功 temp_addr = interfaces; while (temp_addr != NULL) { if( temp_addr->ifa_addr->sa_family == AF_INET) { // Check if interface is en0 which is the wifi connection on the iPhone if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) { // Get NSString from C String address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; } } temp_addr = temp_addr->ifa_next; } } freeifaddrs(interfaces); NSLog(@"手机的IP是:%@", address); return address; } @end
override func viewDidLoad() { super.viewDidLoad() var ipAddress = GetIPAddress.deviceIPAdress()//这是一个类方法,可以直接通过类名调用; var dialog = UIAlertView() dialog.title = "本机IP" dialog.message = ipAddress dialog.show() }
github主页:https://github.com/chenyufeng1991 。欢迎大家访问!