ios - 尝试在 iPhone 上快速获取 IP 地址时出错

标签 ios iphone xcode swift ip-address

我正在尝试获取 iPhone IP 地址并且我正在使用此示例:

我收到此错误: fatal error :在展开可选值时意外发现 nil 并且代码停止听到:

        0x285160 :  bl     0x2ba61c                  ; function signature specialization  of Swift.(_fatalErrorMessage (Swift.StaticString, Swift.StaticString, Swift.StaticString, Swift.UInt) -> ()).(closure #2)
    ->  0x285164 :  trap 

i have a xxx-Bridging-Header.h in my project but i still get this error

   #import <Foundation/Foundation.h>
   #include <arpa/inet.h> 
   #include <sys/socket.h>
   #include <ifaddrs.h>
   @interface NSObject ()
   @end

swift 类

import Foundation
public class NetworkUtils:NSObject{

public func getIFAddresses() -> [String] {
    var addresses = [String]()

    // Get list of all interfaces on the local machine:
    var ifaddr : UnsafeMutablePointer<ifaddrs> = nil
    if getifaddrs(&ifaddr) == 0 {

        // For each interface ...
        for (var ptr = ifaddr; ptr != nil; ptr = ptr.memory.ifa_next) {
            let flags = Int32(ptr.memory.ifa_flags)
            var addr = ptr.memory.ifa_addr.memory

            // Check for running IPv4, IPv6 interfaces. Skip the     loopback interface.
            if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
                if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {

                    // Convert interface address to a human readable string:
                    var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
                    if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),
                        nil, socklen_t(0), NI_NUMERICHOST) == 0) {
                            if let address = String.fromCString(hostname) {
                                addresses.append(address)
                            }
                    }
                }
            }
        }
        freeifaddrs(ifaddr)
    }

    return addresses
 }
}

调用函数

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
   // var osMajorVer:Int
    let osMajorVer:Int = getMajorSystemVersion()
    switch osMajorVer
    {
    case 8:
        var types: UIUserNotificationType = UIUserNotificationType.Badge |
            UIUserNotificationType.Alert |
            UIUserNotificationType.Sound

        var settings: UIUserNotificationSettings = UIUserNotificationSettings( forTypes: types, categories: nil )

        application.registerUserNotificationSettings( settings )
        application.registerForRemoteNotifications()

        break
    case 7:
        application.registerForRemoteNotificationTypes( UIRemoteNotificationType.Badge |
            UIRemoteNotificationType.Sound |
            UIRemoteNotificationType.Alert )
        break
    default:
        break
    }
    var IP:NetworkUtils!
    var ip = IP.getIFAddresses()
    var bounds: CGRect = UIScreen.mainScreen().bounds
    var witdh:Int  = Int(bounds.size.width)
    var height:Int  = Int(bounds.size.height)

    let os = "iPhone"
    var ver = String(osMajorVer)

    let userDefaults = NSUserDefaults.standardUserDefaults()

    userDefaults.setValue("iPhone", forKey: "os")
    userDefaults.setValue("iPhone", forKey:"osType")
    userDefaults.setValue(String(osMajorVer), forKey:"ver")
    userDefaults.setValue(height, forKey:"height")
    userDefaults.setValue(witdh, forKey:"witdh")
    userDefaults.setValue("1.1.1.1", forKey:"IP")
    userDefaults.synchronize() // don't forget this!!!!
     return true
}

最佳答案

问题与 getIFAddresses() 函数无关。这里

var IP:NetworkUtils!
var ip = IP.getIFAddresses()

您将 IP 声明为隐式展开的可选。既然你从不 分配 NetworkUtilsinstance 给它,它是 nil (这是 隐式解包选项的默认值)。 因此第二行导致异常。

你可能想要做的是

let IP = NetworkUtils()
let ip = IP.getIFAddresses()

或者,您可以将 getIFAddresses() 声明为类型(类)方法:

public class NetworkUtils:NSObject{

    public class func getIFAddresses() -> [String] { ... }

}

并将其用作

let ip = NetworkUtils.getIFAddresses()

关于ios - 尝试在 iPhone 上快速获取 IP 地址时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31903334/

相关文章:

iphone - 向 iPhone 发送 HTTP 请求?

ios - 确定用户是否可以看到按钮

ios - 在带有 subview 的 UITableView 中滚动的性能真的很差

objective-c - 关闭 UITableView 静态单元格中的复选标记

ios - 重命名 Xcode 项目后出现 NSKeyedUnarchiver 错误

iphone - 我们可以在 iOS 设备上使用 Mapkit 框架在 Google map 上显示 KML 数据吗?

ios - 如何使用 SwiftAddressBook 操作 iOS 联系人?

iphone - 上传文件

objective-c - 如何防止 UIView 背景旋转?

ios - 如何按 NSArray 内对象内的对象对 NSArray 进行排序?