Shimon Wiener
Shimon Wiener

Reputation: 1180

Error when trying to get IP address in swift on iPhone

Im trying to get an iPhone IP address and i'm using this sample:

I'm getting this error:fatal error: unexpectedly found nil while unwrapping an Optional value and the code stops hear:

        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

the swift class

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
 }
}

Calling 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
}

Upvotes: 0

Views: 1400

Answers (1)

Martin R
Martin R

Reputation: 539815

The problem is unrelated to the getIFAddresses() function. Here

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

you declare IP as an implicitly unwrapped optional. Since you never assign an instance of NetworkUtils to it, it is nil (which is the default value for implicitly unwrapped optionals). Therefore the second line causes the exception.

What you probably want to do is

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

Alternatively, you could declare getIFAddresses() as a type (class) method:

public class NetworkUtils:NSObject{

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

}

and use it as

let ip = NetworkUtils.getIFAddresses()

Upvotes: 2

Related Questions