2015年7月31日 星期五

[Swift] Using NSNetService for Multiple Device Resolution

Apple Official Docs suggest that to persist a bonjour connection, we should save the service name/domain/type and use NSNetService to resolve the IP Address of this service. Obviously this is to cope with IP being dynamic.

NSNetService is actually pretty simple to use after some research. New an NSNetService Object and initiate a search with resolveWithTimeout.

1
2
3
4
var service: NSNetService!
service = NSNetService(domain: serviceDomain, type: serviceType, name: serviceName)
service.delegate = self
service.resolveWithTimeout(3)

Implement the following protocol according to what you what to do in each case:
netServiceDidResolveAddress(sender: NSNetService)
netServiceDidStop(sender: NSNetService)
netService(sender: NSNetService, didNotResolve errorDict: [NSObject : AnyObject])

When a device is detected, the App will enter netServiceDidResolveAddress. After 3 Seconds, it will enter netServiceDidStop. If the resolve address process failed, it will enter the last protocol function.

The above code will work for only 1 device because service is created within a function and it will go out of scope after this function has been executed. If the App is to be able to resolve multiple device at the same time, we must somehow preserve this object and prevent it from going out of scope. The most common method is to save the NSNetService in an Array:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
var allService: NSMutableArray = NSMutableArray()

func populateDevicesList(deviceArray:Array<Array<String>>)
{
    //omitted
    for deviceSet in 0..<deviceArray.count{
        var name = deviceArray[deviceSet][0]
        var type = deviceArray[deviceSet][1]
        var domain = deviceArray[deviceSet][2]
        
        var service: NSNetService!
        service = NSNetService(domain: serviceDomain, type: serviceType, name: serviceName)
        service.delegate = self
        service.resolveWithTimeout(GlobalVariable.TIMEOUT)
        
        allService.addObject(service as NSNetService)
    }
    //omitted
}


The key to multiple device resolution is line 17, saving the NSNetService into an NSMutableArray.

I have also removed the NSNetService object on netServiceDidStop and netService(:didNotResolve:) by using allService.removeLastObject().

沒有留言:

張貼留言