尝试在iPhone上使用swift获取IP地址时出错

时间:2015-08-09 10:41:04

标签: ios iphone xcode swift ip-address

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

我收到此错误:致命错误:在解包可选值时意外发现nil 并且代码停止听到:

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

我的项目中有一个xxx-Bridging-Header.h 但我仍然得到这个错误

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

快速班

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

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
}

1 个答案:

答案 0 :(得分:2)

问题与getIFAddresses()功能无关。这里

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

您将IP声明为隐式解包的可选项。既然你永远不会 为NetworkUtils分配一个实例,它是nil(即。{ 隐式解包的选项的默认值)。 因此第二行会导致异常。

您可能想要做的是

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

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

public class NetworkUtils:NSObject{

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

}

并将其用作

let ip = NetworkUtils.getIFAddresses()