Just An Application

November 15, 2015

Reading QR Codes using the iOS AV Foundation Framework: Prerequisites

Having discovered that one of my iOS applications just maybe needed to be able to read a QR code I was pleased to discover that from iOS 7.0 onwards it is possible to do so using the AV Foundation framework.

There was little bit of trial and error involved in working out how to do set up but after that it “just worked” as they say

1.0 A Session

The first thing we need is a session

    let session = AVCaptureSession()

2.0 An Input

An AVCaptureSession needs an input, an instance of AVCaptureInput, from which to capture things.

In our case we need the input from a camera which, in the context of the AV Foundation framework, is a kind of AVCaptureDevice associaed with the media type

    AVMediaTypeVideo

We can obtain the default device for capturing a given media type by calling the AVCaptureDevice method

    class func defaultDeviceWithMediaType(_ mediaType: String!) -> AVCaptureDevice!

or, alternatively, all the devices capable of capturing a given media type by calling the AVCaptureDevice method

    class func devicesWithMediaType(_ mediaType: String!) -> [AnyObject]!

Using the first method we can do

    ...
    
    if let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    {
       ...
    }

    ...

On an iPad or an iPhone running iOS 9.0 this returns the ‘back camera’.

If we want to ensure that we get the ‘back camera’, rather than just hoping we do, we can do

    ...
    
    if let objects = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
    {
        for device in objects
        {
            if device.position == .Back
            {
                ...
            }
        }
    }
    
    ...

Once we have our desired device we can contruct an instance of AVCaptureDeviceInput which is a sub-class of AVCaptureInput

    let input = try AVCaptureDeviceInput(device:device)

amd then add it to the session

    session.addInput(input)

3,0 An Output

To identify the QR code(s) if any, in the input from the camera we need an instance of the class AVCaptureMetadataOutput.

    let output = AVCaptureMetadataOutput()

We can then add this to the session as an output.

    session.addOutput(output)

An AVCaptureMetadataOutput object is capable of recognizing more than just QR codes.

To find out exactly what we can access the availableMetadataObjectTypes property.

On an iPad running iOS 9.0 the following code

    ...
    
    for o in output.availableMetadataObjectTypes
    {
        print(o)
    }
    
    ...

produces this output

    ...

    org.iso.Aztec
    org.iso.Code128
    org.iso.Code39
    org.iso.Code39Mod43
    com.intermec.Code93
    org.iso.DataMatrix
    org.gs1.EAN-13
    org.gs1.EAN-8
    org.ansi.Interleaved2of5
    org.gs1.ITF14
    org.iso.PDF417
    org.iso.QRCode
    org.gs1.UPC-E
    face
    
    ...

and on an iPhone running iOS 9.0 this output

    ...

    face
    org.iso.Aztec
    org.iso.Code128
    org.iso.Code39
    org.iso.Code39Mod43
    com.intermec.Code93
    org.iso.DataMatrix
    org.gs1.EAN-13
    org.gs1.EAN-8
    org.ansi.Interleaved2of5
    org.gs1.ITF14
    org.iso.PDF417
    org.iso.QRCode
    org.gs1.UPC-E

    ...

To specify that we are only interested in QR codes we can set the metadataObjectTypes property.

    output.metadataObjectTypes = [AVMetadataObjectTypeQRCode]

Note

In the AVCaptureMetadataOutput case the order in which the input and output are added is significant.

If it is added before the camera input then the availableMetadataTypes property is simply an empty array and attempting to set the metadataTypes property will result in an NSInvalidArgumentException being thrown.

4.0 A Delegate

An AVCaptureMetadataOutput object passes metadata objects obtained from the input to a delegate which is required to implement the AVCaptureMetadataOutputObjectsDelegate protocol.

The AVCaptureMetadataOutputObjectsDelegate protocol defines a single method

    optional func captureOutput(
                      _
                          captureOutput:
                              AVCaptureOutput!,
                      didOutputMetadataObjects
                          metadataObjects:
                              [AnyObject]!,
                      fromConnection
                          connection:
                              AVCaptureConnection!)

Each element of the array passed as the metadataObjects argument is an instance of a sub-class of the class AVMetadataObect.

In the case of a QR code the element will be an instance of the class AVMetadataMachineReadableCodeObject.

The value of the stringValue property of an instance of AVMetadataMachineReadableCodeObject is a human readable version of, in this case, the QR code.

    func captureOutput(
             captureOutput:
                 AVCaptureOutput!,
             didOutputMetadataObjects
                 metadataObjects: [AnyObject]!,
             fromConnection
                 connection:
                    AVCaptureConnection!)
    {
        for metadataObject in metadataObjects
        {
            if metadataObject.type == AVMetadataObjectTypeQRCode
            {
                let value = metadataObject.stringValue
                
                ...
            }
        }
    }

The delegate for an AVCaptureMetadataOutput object can be set using the method

    public func setMetadataObjectsDelegate(
                    objectsDelegate:
                        AVCaptureMetadataOutputObjectsDelegate!,
                    queue
                        objectsCallbackQueue:
                            dispatch_queue_t!)

The queue argument specifies the dispatch queue on which the delegate's method will be invoked.


Copyright (c) 2015 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog's author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

August 24, 2015

Drawing Triangles For Fun And Profit, Or How To Make Your Popovers Stand Out From The Crowd

Filed under: iOS, Swift, UIKIt, UIPopoverBackgroundView — Tags: , , , — Simon Lewis @ 11:02 am

If have you have ever wanted to make the arrows of your popovers that little bit more ‘pointy’, or you have hankered after a co-respondent popover, for example

Popover

then help is at hand courtesy of the UIPopoverBackgroundView class.

The UIPopoverBackgroundView Class

The UIPopoverBackgroundView class defines two properties.

The arrowDirection Property

    var arrowDirection: UIPopoverArrowDirection

The documentation for this reads

The direction in which the popover arrow is pointing.

which is entirely obvious unless it is not.

A picture sometimes helps.

Arrows And Their Directions

UpDownLeftRight

The arrowOffset Property

    var arrowOffset: CGFloat

The documentation uses a lot of words to explain this.

Here are some pictures instead

Offset For Vertical Arrows

VerticalOffsets

Offset For Horizontal Arrows

HorizontalOffsets

The UIPopoverBackgroundViewMethods Protocol

The UIPopoverBackgroundView class implements the UIPopoverBackgroundViewMethods protocol

The arrowBase Method

    static func arrowBase() -> CGFloat

Note that this is a static, i.e., class method

The base of an arrow (see below) must be the same for all directions and it must not change.

The arrowHeight Method

    static func arrowHeight() -> CGFloat

Note that this is a static, i.e., class method

The height of an arrow (see below) must be the same for all directions and it must not change.

The contentViewInsets Method

    static func contentViewInsets() -> UIEdgeInsets

Note that this is a static, i.e., class method

This method specifies the distances between the edges of the popover’s content and the edges of the background view’s frame. exclusive of the arrow.

Arrow Bases And Heights

BaseHeight

Subclassing The UIPopoverBackgroundView Class

The only way to make use of the UIPopoverBackgroundView class is to sub-class it and override both it properties and the three methods defined by the UIPopoverBackgroundViewMethods protocol.

The arrowDirection Property

It is not possible to override the arrowDirection property with a stored property so we need to define a computed
property.

To start with we don’t really know what we should be doing when getting or setting the value but the pseudo-code looks like this

    override var arrowDirection : UIPopoverArrowDirection
    {
        get
        {
            return ????
        }
    
        set
        {
            ???? = newValue
        }
    }

The arrowOffset Property

The same holds true for the arrowOffset property. It needs to be overridden by a computed property and we don’t really know what we will need to do.

    override var arrowOffset : CGFloat
    {
        get
        {
            return ????
        }
        
        set
        {
            ???? = newValue
        }
    }

The arrowBase Method

This is a ‘class’ method so there is not a lot of room for manoeuvre, We will will need to return some kind of constant value obtained from somewhere.

    override static func arrowBase() -> CGFloat
    {
        return ????
    }

The arrowHeight Method

The same is true for the arrowHeight method.

    override static func arrowHeight() -> CGFloat
    {
        return ????
    }

The contentViewInsets Method

This one we can do straight away

    override static func contentViewInsets() -> UIEdgeInsets
    {
        return UIEdgeInsets(top: 10.0, left: 10.0, bottom:10.0, right: 10.0)
    }

but its really not that exciting.

A Direction Digression Or When Is An Enum Not An Enum ?

For our purposes the arrow direction can be one of

  • Up

  • Down

  • Left

  • Right

This can be represented by the Swift enum

    enum Direction
    {
        case UP
        case DOWN
        case LEFT
        case RIGHT
    }

which results in switch statements that look like this

    switch direction
    {
        case .UP:
    
            ...
            
        case .DOWN:
        
            ...
            
        case .LEFT:
        
            ...
            
        case .RIGHT:
        
            ...
    }

What the API uses to represent the direction of an arrow is the type

    UIPopoverArrowDirection

which results in switch statements that look like this

    switch direction
    {
        case UIPopoverArrowDirection.Up:
    
            ...
    
        case .UIPopoverArrowDirection.Down:
    
            ...
    
        case .UIPopoverArrowDirection.Left:
    
            ...
    
        case .UIPopoverArrowDirection.Right:
    
            ...
            
        default:
        
            ...
    }

because in Swift UIPopoverArrowDirection is not an enum at all.

In Objective-C UIPopoverArrowDirection is defined like this

    typedef NSUInteger UIPopoverArrowDirection;

There are some associated constants defined using an anonymous enum

    enum {
        UIPopoverArrowDirectionUp = 1UL << 0,
        UIPopoverArrowDirectionDown = 1UL << 1,
        UIPopoverArrowDirectionLeft = 1UL << 2,
        UIPopoverArrowDirectionRight = 1UL << 3,
        UIPopoverArrowDirectionAny = UIPopoverArrowDirectionUp | UIPopoverArrowDirectionDown |
        UIPopoverArrowDirectionLeft | UIPopoverArrowDirectionRight,
        UIPopoverArrowDirectionUnknown = NSUIntegerMax
    };

This is a standard ‘C’ idiom which makes it possible to specify both an arrow direction and a set of arrow directions as values of the ‘type’ UIPopoverArrowDirection.

This translates to something like the following in Swift

    struct UIPopoverArrowDirection : RawOptionSetType {
        init(_ rawValue: UInt)
        init(rawValue rawValue: UInt)
        static var Up: UIPopoverArrowDirection { get }
        static var Down: UIPopoverArrowDirection { get }
        static var Left: UIPopoverArrowDirection { get }
        static var Right: UIPopoverArrowDirection { get }
        static var Any: UIPopoverArrowDirection { get }
        static var Unknown: UIPopoverArrowDirection { get }
    }

which provides a bit of syntactic sugar, and a little more type safety in that you cannot accidentally pass any old UInt to something expecting a UIPopoverArrowDirection value. Now you have to wrap it in a struct first !

In our case, semantically at least, the API shouldn’t be passing a value that is not equal to one of the static values Up, Down, Left, or Right but as the compiler is making clear there is nothing to stop it doing so programatically, hence the need for a ‘default’ case.

The problem with having to deal with a default case is that increases the complexity of the code for no gain whatsoever.

Each time we switch on a value of ‘type’ UIPopoverArrowDirection we have to decide what the ‘right thing’ to do is in the default case, even if that thing is nothing.

If we change the code containing the switch then the decision needs to be taken once again.

If we need to add another switch you need to make the decision again.

Its much easier and safer to work with values of type Direction internally, converting from the UIPopoverArrowDirection value at the point it is set and converting back again when the value is accessed

We can extend Direction quite simply to do the conversions for us

    extension Direction
    {
        static func fromPopoverArrowDirection(direction:UIPopoverArrowDirection) -> Direction?
        {
            switch direction
            {
                case UIPopoverArrowDirection.Up:
    
                    return .UP
    
                case UIPopoverArrowDirection.Down:
    
                    return .DOWN
    
                case UIPopoverArrowDirection.Left:
    
                    return .LEFT
    
                case UIPopoverArrowDirection.Right:
    
                    return .RIGHT
    
                default:
    
                    return nil
            }
        }
    
        func toPopoverArrowDirection() -> UIPopoverArrowDirection
        {
            switch self
            {
                case .UP:
    
                    return UIPopoverArrowDirection.Up
    
                case .DOWN:
    
                    return UIPopoverArrowDirection.Down
    
                case .LEFT:
    
                    return UIPopoverArrowDirection.Left
    
                case .RIGHT:
    
                    return UIPopoverArrowDirection.Right
            }
        }
    }

We’re Going To Need An ‘Arrow’

So far its been all arrows all the time so let’s define a nifty structure to hold all the arrow related stuff

    private struct Arrow
    {
        let height    : CGFloat   = 30.0
        let base      : CGFloat   = 20.0
    
        var direction : Direction = .UP
        var offset    : CGFloat   = 0.0
    }

a variable for storing one

    private var arrow  : Arrow = Arrow()

and a ‘prototype’ arrow for the static methods to access

    private static let PROTO_ARROW = Arrow()

New And Improved

We can now flesh out the implementations of the overridden methods and properties like so

    override static func arrowBase() -> CGFloat
    {
        return PROTO_ARROW.base
    }
    override static func arrowHeight() -> CGFloat
    {
        return PROTO_ARROW.height
    }

For the arrowDirection property, if we are ever handed an ‘invalid’ UIPopoverArrowDirection value we simply drop it on the floor. Its not clear what else we could do.

    override var arrowDirection : UIPopoverArrowDirection
    {
        get
        {
            return arrow.direction.toPopoverArrowDirection()
        }
    
        set
        {
            if let direction = Direction.fromPopoverArrowDirection(newValue)
            {
                arrow.direction = direction
            }
        }
    }
    override var arrowOffset: CGFloat
    {
        get
        {
            return arrow.offset
        }
    
        set
        {
            arrow.offset = newValue
        }
    }

Now What ?

Now we have to provide the ‘background’ for the popover.

By default the background is simply an arrow plus a rectangle.

In theory we could draw it but the documentation states that we should use images.

To do this we need to add two instances of UIImageView as subviews, one for the arrow and one for the ‘rest’

BasicBackground

The basic task is to work out where the two components of the background should go.

We need to set the frames of the two subviews on the basis of the arrow base and height, and the current values for the arrow’s direction and offset.

We can define a method on the Arrow struct which returns its frame given the bounds of its super view

    func frame(container:CGRect) -> CGRect
    {
        let containerMidX   = CGRectGetMidX(container)
        let containerMidY   = CGRectGetMidY(container)
        let containerWidth  = container.size.width
        let containerHeight = container.size.height
    
        let halfBase        = base/2.0
    
        let x    : CGFloat
        let y    : CGFloat
        let size : CGSize = frameSize()
    
        switch direction
        {
            case .UP:
    
                x = containerMidX + offset - halfBase
                y = 0.0
    
            case .DOWN:
    
                x = containerMidX + offset - halfBase
                y = containerHeight - height
    
            case .LEFT:
    
                x = 0.0
                y = containerMidY + offset - halfBase
    
            case .RIGHT:
    
                x = containerWidth - height
                y = containerMidY + offset - halfBase
        }
        return CGRect(x: x, y: y, width:size.width, height:size.height)
    }

When the arrow is ‘vertical’ the x coordinate of the origin is the same, and the arrow is either at the ‘top’ if the direction is .UP, or at the bottom if the direction is .DOWN.

When the arrow is ‘horizontal’ the y coordinate of the origin is the same and the arrow is on the left if the direction is .LEFT or on the right if the direction is .RIGHT.

This method calls the frameSize method

    private func frameSize() -> CGSize
    {
        switch direction
        {
            case .UP,
                 .DOWN:
    
                return CGSize(width: base, height: height)
    
            case .LEFT,
                 .RIGHT:
    
                return CGSize(width: height, height: base)
        }
    }

Since the layout is a function of the current values of the arrow’s direction and offset we need to add calls to the setNeedLayout method each time either of these values change.

    override var arrowDirection : UIPopoverArrowDirection
    {
        get
        {
            return arrow.direction.toPopoverArrowDirection()
        }
    
        set
        {
            if let direction = Direction.fromPopoverArrowDirection(newValue)
            {
                arrow.direction = direction
                setNeedsLayout()
            }
        }
    }
    override var arrowOffset: CGFloat
    {
        get
        {
            return arrow.offset
        }
    
        set
        {
            arrow.offset = newValue
            setNeedsLayout()
        }
    }

This ensures that the layoutSubviews method will be called when necessary.

    override func layoutSubviews()
    {
        let arrowFrame      = arrow.frame(self.bounds)
        var backgroundFrame = self.bounds
    
        switch arrow.direction
        {
            case .UP:
    
                backgroundFrame.origin.y    += arrowFrame.height
                backgroundFrame.size.height -= arrowFrame.height
    
            case .DOWN:
    
                backgroundFrame.size.height -= arrowFrame.height
    
            case .LEFT:
    
                backgroundFrame.origin.x   += arrowFrame.width
                backgroundFrame.size.width -= arrowFrame.width
    
            case .RIGHT:
    
                backgroundFrame.size.width -= arrowFrame.width
        }
    
        backgroundView?.frame = backgroundFrame
    
        arrowView?.image = arrowImages[arrow.direction]
        arrowView?.frame = arrowFrame
    }

Wiring It All Up

To get our UIPopoverBackgroundView sub-class to be used for a popover being presented via a segue we need to set the property

   var popoverBackgroundViewClass: AnyObject.Type?

of the UIPopoverPresentationController instance, managing the popover’s display.

This can be done in the appropriate prepareForSegue method

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
    {
        if let segueId = segue.identifier
        {
            switch segueId
            {
                case "CustomPopoverSegue":
    
                    let dvc = segue.destinationViewController as? UIViewController
                    let ppc = dvc?.popoverPresentationController
    
                    ppc?.popoverBackgroundViewClass = CustomPopoverBackgroundView.self
    
                default:
    
                    break
            }
        }
    }

Note that it is the class itself not an instance of the class which is assigned to the property.

About That Arrow Drawing …

It turns out that no actual drawing of arrows is required at runtime which is a bit disappointing.

This is not strictly true, you can draw them, it does appear to work, but you are supposed to use images.

You can, if you wish, use a single image and rotate it as necessary.

Alternatively, for those of us who do not entirely trust affine transformations, after all how do you know what they are really doing ?, you simply have one image for each direction, which you can of course draw, so all is not lost.

Here’s some very simple code for drawing a triangle on Mac OS X.

    func drawArrow(width:Int, height:Int, vertices:(CGPoint, CGPoint, CGPoint), colour:NSColor) -> NSData?
    {
        let bitmap = NSBitmapImageRep(
                         bitmapDataPlanes:
                             nil,
                         pixelsWide:
                             width,
                         pixelsHigh:
                             height,
                         bitsPerSample:
                             8,
                         samplesPerPixel:
                             4,
                         hasAlpha:
                             true,
                         isPlanar:
                             false,
                         colorSpaceName:
                             NSCalibratedRGBColorSpace,
                         bytesPerRow:
                             (4 * width),
                         bitsPerPixel:
                             32)
        
        NSGraphicsContext.saveGraphicsState()
        NSGraphicsContext.setCurrentContext(NSGraphicsContext(bitmapImageRep:bitmap!))
        
        let (v0, v1, v2) = vertices
        
        let path = NSBezierPath()
        
        path.moveToPoint(v0)
        path.lineToPoint(v1)
        path.lineToPoint(v2)
        path.lineToPoint(v0)
        path.closePath()
        
        colour.setFill()
        
        path.fill()
        
        NSGraphicsContext.restoreGraphicsState()
        
        return bitmap?.representationUsingType(.NSPNGFileType, properties: [NSObject: AnyObject]())
    }

Copyright (c) 2015 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

June 27, 2014

So Swift Then ? Or Wot No Brackets ?

So Swift is essentially Objective-C without the C and without the bracket message sending syntax and with some new stuff and some changed stuff.

Well the C is no loss but the brackets are the best bit so what new stuff do we get to compensate for their disappearance ?

In no particular order

  • tuples

  • a first class enum type

  • a first class struct type

  • operator functions and custom operators

  • range operators

  • subscript operators

  • optional values

  • generics

  • a super switch

  • a plethora of options for parameter lists

and

    much much more

as it always says on the posters.


Copyright (c) 2014 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

November 20, 2013

Service Discovery In Android And iOS: Part Eight – iOS Take Four

If DNSServiceBrowse and friends are not to your liking there is always the function DNSServiceQueryRecord which enables us to obtain DNS records directly.

1.0 DNSServiceQueryRecord

The DNSServiceQueryRecord function declaration follows the common function pattern and looks like this

    DNSServiceErrorType DNSServiceQueryRecord(
                            DNSServiceRef*             sdRef,
                            DNSServiceFlags            flags,
                            uint32_t                   interfaceIndex,
                            const char*                fullname,
                            uint16_t                   rrtype,
                            uint16_t                   rrclass,
                            DNSServiceQueryRecordReply callBack,
                            void*                      context);

The fullname should be the absolute name of the node for which the record or records are being requested.

The rrtype should be the type of the record or records being requested.

The rrclass should be the class of the record or records being requested.

If the kDNSServiceFlagsTimeout bit is set in the flags argument then the function will timeout after a system dependent amount of time.

2.0 The DNSServiceQueryRecord Callback Function

The callback function will be invoked

  • once for each record that is received in response to the query

  • once for each record that is received in response to the query that subsequently expires

  • if an error occurs

  • if a timeout occurs

3.0 DNSServiceQueryRecordReply

The DNSServiceQueryRecordReply function type declaration follows the common function type pattern and looks like this

    typedef void (*DNSServiceQueryRecordReply)(
                       DNSServiceRef       sdRef,
                       DNSServiceFlags     flags,
                       uint32_t            interfaceIndex,
                       DNSServiceErrorType errorCode,
                       const char*         fullname,
                       uint16_t            rrtype,
                       uint16_t            rrclass,
                       uint16_t            rdlen,
                       const void*         rdata,
                       uint32_t            ttl,
                       void*               context);

When a function of this type is invoked, then, if the errorCode argument is kDNSServiceErr_NoError

  • fullname is the absolute name of the node with the record is associated

  • rrtype is the type of the record

  • rrclass is the class of the record.

  • rdlen is the length of the record data

  • rdate is the record data

  • ttl is the time in seconds for which the record is valid

The flags argument will have the kDNSServiceFlagsAdd bit set if the callback is being invoked when a record is received in response to the query.

If kDNSServiceFlagsAdd bit is clear then callback is being invoked because the record has expired,
in which case the ttl argument will be 0.

If a timeout occurs the value of the errorCode argument will be kDNSServiceErr_Timeout.

3.0 The Query Class

We can encapsulate the call to DNSServiceQueryRecord and its associated callback function in a class
like so

    //
    //  Query.m
    //  XperTakeFour
    //
    //  Created by Simon Lewis on 08/11/2013.
    //  Copyright (c) 2013 Simon Lewis. All rights reserved.
    //
        
    #import <dns_sd.h>
        
    #import "QueryDelegate.h"
    #import "Record.h"
        
    #import "Query.h"
        
    @interface Query()
        
    @property NSString* name;
    @property uint16_t  type;
    @property uint16_t class;
        
    - (void)record:(const Record*)theRecord onInterface:(uint32_t)theIndex;
        
    - (void)recordExpired:(const Record*)theRecord;
        
    - (void)failed:(DNSServiceErrorType)theName;
        
    @end
        
    @implementation Query
    {
        DNSServiceRef   ref;
    }
        
    - (Query*)init:(NSString*)theName type:(uint16_t)theType class:(uint16_t)theClass
    {
        self = [super init];
        if (self != nil)
        {
            self.name  = theName;
            self.type  = theType;
            self.class = theClass;
        }
        return self;
    }
    
    static void queryCallback(
                    DNSServiceRef       sdRef,
                    DNSServiceFlags     theFlags,
                    uint32_t            theInterfaceIndex,
                    DNSServiceErrorType theErrorCode,
                    const char*         theName,
                    uint16_t            theType,
                    uint16_t            theClass,
                    uint16_t            theDataLength,
                    const void*         theData,
                    uint32_t           theTTL,
                    void*               theContext)
    {
        NSLog(@"queryCallback: flags == %d error code == %d", theFlags, theErrorCode);
        
        if (theErrorCode != kDNSServiceErr_NoError)
        {
            [(__bridge Query*)theContext failed:theErrorCode];
        }
        else
        {
            NSLog(@"theName == %s theType == %u", theName, theType);
        
            Record rr = {
                            theName,
                            theType,
                            theClass,
                            theTTL,
                            theDataLength,
                            theData
                        };
        
            if ((theFlags & kDNSServiceFlagsAdd) != 0)
            {
                [(__bridge Query*)theContext record:&rr onInterface:theInterfaceIndex];
            }
            else
            {
                [(__bridge Query*)theContext recordExpired:&rr];
            }
        }
    }
        
        
    - (void)start:(DNSServiceRef)theServiceRef interface:(uint32_t)theInterfaceIndex timeout:(BOOL)timeout
    {
        ref = theServiceRef;
        
        DNSServiceErrorType error;
        DNSServiceFlags     flags;
        
        flags = kDNSServiceFlagsShareConnection;
        if (timeout)
        {
            flags |= kDNSServiceFlagsTimeout;
        }
        error = DNSServiceQueryRecord(
                    &ref,
                    flags,
                    theInterfaceIndex,
                    [self.name UTF8String],
                    self.type,
                    self.class,
                    queryCallback,
                    (__bridge void*)self);
        if (error != kDNSServiceErr_NoError)
        {
            NSLog(@"DNSServiceQueryRecord: %d", error);
            [self.delegate queryDidFail:self withError:error];
        }
    }
        
    - (void)record:(const Record*)theRecord onInterface:(uint32_t)theIndex
    {
        [self.delegate query:self didGetResponse:theRecord onInterface:theIndex];
    }
        
    - (void)recordExpired:(const Record *)theRecord
    {
        [self.delegate query:self recordDidExpire:theRecord];
    }
        
    - (void)failed:(DNSServiceErrorType)theErrorCode
    {
        if (theErrorCode != kDNSServiceErr_Timeout)
        {
            [self.delegate queryDidFail:self withError:theErrorCode];
        }
        else
        {
            [self.delegate queryDidTimeout:self];
        }
    }
        
    @end

4.0 Using The Query Class

The start method of FindServices v4 starts the search by querying for PTR records associated with the service type node.

    ...
    
    - (BOOL)start
    {
        DNSServiceErrorType error = DNSServiceCreateConnection(&dnsServiceRef);
        
        if (error != kDNSServiceErr_NoError)
        {
            NSLog(@"Error: DNSServiceCreateConnection %d", error);
            return NO;
        }
        error = DNSServiceSetDispatchQueue(dnsServiceRef, dispatch_get_main_queue());
        if (error != kDNSServiceErr_NoError)
        {
            NSLog(@"Error: DNSServiceSetDispatchQueue %d", error);
            return NO;
        }
        self.ptrQuery = [[Query alloc] init:self.type type: kDNSServiceType_PTR class:kDNSServiceClass_IN];
        self.ptrQuery.delegate = self;
        [self.ptrQuery start:dnsServiceRef interface:kDNSServiceInterfaceIndexAny timeout:NO];
        return YES;
    }
    
    ...

5.0 Examples

I will forgo the output from the examples as there is only so many console log messages anybody can be expected to find interesting.

Needless to say everything works in pretty much the same way as it did in the three preceding incarnations of the
FindServices class.


Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

November 18, 2013

Service Discovery In Android And iOS: Part Seven – iOS Take Three: Down At C Level

For anyone who considers both Foundation and Core Foundation too rarified there is always a C function API for performing DNS/mDNS based service discovery and registration.

This is declared in the header file

    /usr/include/dns_sd.h

1.0 DNSServiceRefs And Connection Sharing

By default each function in the API which requires DNS functionality establishes a separate connection to the DNS service which it returns as a DNSServiceRef.

In this context the name DNSServiceRef can be a bit confusing.

A DNSServiceRef is a reference to the DNS Service, that is, the thing doing the search for services using DNS, not a reference to a service found using DNS.

There is an alternative to having a per function call connection and DNSServiceRef.

A connection to the DNS service can be established separately and then shared by passing it to each function that would otherwise create a new connection.

2.0 The Function Pattern

All the functions in the API which access the DNS service are declared using a common pattern

    DNSServiceErrorType <function-name>(
                            DNSServiceRef*           sdRef,
                            DNSServiceFlags          flags,
                            uint32_t                 interfaceIndex,
        
                            ... <function specific arguments> ...
    
                            <function specific type> callBack,
                            void*                    context);

2.1 The sdRef Argument

    DNSServiceRef*  sdRef

The sdRef argument is either

  • a pointer to an uninitalized DNSServiceRef which will be initialized to a valid DNSServiceRef if the call succeeds, or

  • a pointer to a shared DNSServiceRef which should be used by the function

2.2 The flags argument

    DNSServiceFlags flags

The flags argument unsurprisingly specifies zero or more flags. If an initialized DNSServiceRef is being passed via the sdRef argument then the flag

    kDNSServiceFlagsShareConnection

must be set.

2.3 The interfaceIndex Argument

    uint32_t   interfaceIndex

The index of the network interface to use to perform the requested DNS operation(s).

If the specific network interface is not important then when starting the search for services the constant

    kDNSServiceInterfaceIndexAny

can be used.

When a service is found the index of the network interface it is associated with is reported and subsequent calls can use this value.

2.4 The callBack Argument

The type of the callBack argument is specific to the function to which it is being passed but in each case it specifies the function to be invoked when a a result is available or an error occurs.

2.5 The info Argument

    void*  context

The value of the context argument will be passed as an argument to the callback function specified by
the callBack argument.

3.0 The Callback Function Pattern

All the callback function types are declared using a common pattern.

    typedef void (*<type-name>)(
                        DNSServiceRef       sdRef,
                        DNSServiceFlags     flags,
                        uint32_t            interfaceIndex,
                        DNSServiceErrorType errorCode,
    
                        ... <function specific arguments> ...

                        void*               context);

3.1 The sdRef Argument

The DNSServiceRef which was passed to the function which invoked this callback.

3.2 The flags Argument

The flags argument is used to pass general status information, e.g., if the

    kDNSServiceFlagsMoreComing

flag is set then this callback will be invoked again.

3.3 The interfaceIndex Argument

The index of the network interface on which the result was obtained.

3.4 The errorCode Argument

If the errorCode argument is not

    kDNSServiceErr_NoError

then an error has occurred.

3.5 The context Argument

The value of the context argument passed to the function which invoked this callback.

4.0 Searching For Services

4.1 DNSServiceBrowse

We can start the search for services of a given type by using the function DNSServiceBrowse
which is declared like this

    DNSServiceErrorType DNSServiceBrowse(
                            DNSServiceRef*        sdRef,
                            DNSServiceFlags       flags,
                            uint32_t              interfaceIndex,
                            const char*           regtype,
                            const char*           domain,
                            DNSServiceBrowseReply callBack,
                            void*                 context);

The regtype argument should be the domain relative type name, e.g.,

    "_ipp.tcp."

The domain argument should be the absolute name of the domain to search in, e.g.,

    "local."

4.2 The DNSServiceBrowse Callback Function

The function passed as the callBack argument to DNSServiceBrowse will be called once for each service of the given type that is found.

If the information about a service that was found becomes invalid, implying that it has ‘disappeared’, then the callback function will called again.’

4.3 The DNSServiceBrowseReply Function Type

The function type DNSServiceBrowseReply is declared like this

    typedef void (*DNSServiceBrowseReply)(
                       DNSServiceRef       sdRef,
                       DNSServiceFlags     flags,
                       uint32_t            interfaceIndex,
                       DNSServiceErrorType errorCode,
                       const char*         serviceName,
                       const char*         regtype,
                       const char*         replyDomain,
                       void*               context);

When a function of this type is invoked, then if the errorCode argument is kDNSServiceErr_NoError

  • serviceName is the type relative name of the service.

  • regtype is the domain relative name of the service type

  • replyDomainis the absolute name of the domain the service is registered in

The kDNSServiceFlagsAdd flag will be set in the flags argument if the service has been found, and clear if the service has been ‘lost’.

5.0 Resolving Services

Resolving a service involves two functions

    DNSServiceResolve

which obtains the service’s SRV and TXT records, and

and

    DNSServiceGetAddrInfo.

which obtains the address or addresses of the host on which the service is running

5.1 DNSServiceResolve

We can obtain the information contained in the SRV and TXT records associated with a given service by using the function
DNSServiceResolve which is declared like this

    DNSServiceErrorType DNSServiceResolve(
                            DNSServiceRef*         sdRef,
                            DNSServiceFlags        flags,
                            uint32_t               interfaceIndex,
                            const char*            name,
                            const char*            regtype,
                            const char*            domain,
                            DNSServiceResolveReply callBack,
                            void*                  context);

The name argument should be the type relative name of the service.

The regtype argument should be the domain relative name of the service type.

The domain argument should be the absolute name of the domain in which the service is registered.

5.1.1 The DNSServiceResolve Callback Function

The function passed as the callBack argument to DNSServiceResolve will be called once, either with the results of with an error.

5.1.1 The DNSServiceResolveReply Function Type

The function type DNSServiceResolveReply is declared like this

    typedef void (*DNSServiceResolveReply)(
                       DNSServiceRef        sdRef,
                       DNSServiceFlags      flags,
                       uint32_t             interfaceIndex,
                       DNSServiceErrorType  errorCode,
                       const char*          fullname,
                       const char*          hosttarget,
                       uint16_t             port,
                       uint16_t             txtLen,
                       const unsigned char* txtRecord,
                       void*                context);

When a function of this type is invoked, then, if the errorCode argument is kDNSServiceErr_NoError

  • fullname is the absolute name of the service, e.g., "ipp_server_1._ipp._tcp.local.".

  • hosttarget is the name of the host the service is running on.

  • port is the port, in network byte order, the service is listening on.

  • txtLen is is the length of the TXT record data.

  • txtRecord is a pointer to the TXT record data itself.

5.2 DNSServiceGetAddrInfo

We can obtain the address of a host using the function DNSServiceGetAddrInfo which is declared like this

    DNSServiceErrorType DNSServiceGetAddrInfo(
                            DNSServiceRef*             sdRef,
                            DNSServiceFlags            flags,
                            uint32_t                   interfaceIndex,
                            DNSServiceProtocol         protocol,
                            const char*                hostname,
                            DNSServiceGetAddrInfoReply callBack,
                            void*                      context);

If the

    kDNSServiceFlagsTimeout

is set in the flags argument then the operation may timeout after a system defined amount of time.

The protocol argument specifies the type of the address requested.

The value should be one of

  • 0

  • kDNSServiceProtocol_IPv4

  • kDNSServiceProtocol_IPv6

  • kDNSServiceProtocol_IPv4|kDNSServiceProtocol_IPv6

A value of 0 (zero) is usually equivalent to requesting both the IPv4 and IPv6 addresses.

The hostname argument should be the absolute name of the host.

5.2.1 The DNSServiceGetAddrInfo Callback Function

The function passed as the callBack argument to DNSServiceGetAddrInfo will be called once for each address type that was requested and is found

It will also be called if the address of the host becomes invalid, e.g., because the host has been turned off.

5.2.2 The DNSServiceGetAddrInfoReply Function Type

The function type DNSServiceGetAddrInfoReply is declared like this

    typedef void (*DNSServiceGetAddrInfoReply)(
                       DNSServiceRef          sdRef,
                       DNSServiceFlags        flags,
                       uint32_t               interfaceIndex,
                       DNSServiceErrorType    errorCode,
                       const char*            hostname,
                       const struct sockaddr* address,
                       uint32_t               ttl,
                       void*                  context);

When a function of this type is invoked, then, if the errorCode argument is kDNSServiceErr_NoError

  • hostname is the name of the host whose address this is

  • address is a pointer to its address, and

  • ttl is the time in seconds for which the given address is valid

The kDNSServiceFlagsAdd flag will be set in the flags argument if the address has been ‘found’, and clear if the address is no longer valid.

The kDNSServiceFlagsMoreComing will be set in the flags argument if there are more addresses, and will be clear if this is the last address.

The type of the address will of course depend upon what what specified as the protocol argument in the call to DNSServiceGetAddrInfo.

If both IPv4 and IPv6 addresses were requested then it will be necessary to examine the sa_family field of the sockaddr struct to find out which one it is.

6.0 The Care And Maintenance Of Your DNSServiceRef

Something that is not perhaps immediately apparent is that the shared DNSServiceRef or one created by a function like DNSServiceBrowse has to be actively handled on the client side.

There are two ways to do this, either

  • by obtaining the file descriptor associated with the connection by calling DNSServiceRefSockFD and doing it all yourself, or

  • by calling the function DNSServiceSetDispatchQueue which will result in the connection being handled ‘automatically’ on the dispatch queue of your choice.

6.1 DNSServiceRefSockFD

The function DNSServiceRefSockFD is declared like this

    int DNSSD_API DNSServiceRefSockFD(DNSServiceRef sdRef);

It takes a DNSServiceRef and returns the file descriptor of the underlying connection to the DNS service.

Once you have obtained your file descriptor you will need to determine when it is readable.

To do this you are going to need either

  • an fd_set and a system call, or

  • a pollfd struct and a different system call

6.1.1 Using select

To use the select system call and assuming sr is the DNSServiceRef you will need to do something like this.

    ...
    
    int fd = DNSServiceRefSockFD(sr);
    
    if (fd == -1)
    {
        fprintf(stderr, "fd == -1 !");
        return;
    }
    
    fd_set         readFDs;
    struct timeval tv;
    
    while (true)
    {
        FD_ZERO(&readFDs);
        FD_SET(fd, &readFDs);
    
        tv.tv_sec  = 1000000;
        tv.tv_usec = 0;
    
        int status = select(fd + 1, &readFDs, NULL, NULL, &tv);
    
        if (status == -1)
        {
            fprintf(stderr, "status == -1\n");
            break;
        }
        else
        if (status == 0)
        {
            fprintf(stderr, "status == 0\n");
        }
        else
        if (FD_ISSET(fd, &readFDs))
        {
            int error = DNSServiceProcessResult(sr);
    
            if (error != kDNSServiceErr_NoError)
            {
                fprintf(stderr, "DNSServiceProcessResult: error == %d\n", error);
                break;
            }
        }
    }

    ...
    

When the file descriptor is readable the function DNSServiceProcessResult is invoked to handle the input. It is this call that results in callback functions being invoked.

This assumes that you are sharing a single DNSServiceRef if not then you are going to end up knee deep in file descriptors and its all going to get very messy very fast.

6.1.2 Using poll

If the use of select is too retro for you you can always use the new-fangled poll system call.

The code looks very similar because poll is just select with unlimited [1] file descriptors.

    ...

    int fd = DNSServiceRefSockFD(sr);
    
    if (fd == -1)
    {
        NSLog(@"fd == -1 !");
        return;
    }
    
    struct pollfd   pollFD;
    
    while (true)
    {
        pollFD.fd = fd;
        pollFD.events = POLL_IN;
        
        int status = poll(&pollFD, 1 , 1000000);
    
        if (status == -1)
        {
            fprintf(stderr, "status == -1\n");
            break;
        }
        else
        if (status == 0)
        {
            fprintf(stderr, "status == 0\n");
        }
        else
        if ((pollFD.revents & POLL_IN) != 0)
        {
            int error = DNSServiceProcessResult(sr);

            if (error != kDNSServiceErr_NoError)
            {
                fprintf(stderr, "DNSServiceProcessResult: error == %d\n", error);
                break;
            }
        }
    }

    ...

6.2 DNSServiceSetDispatchQueue

The alternative to wrestling with file descriptors is the function DNSServiceSetDispatchQueue
which is declared like this

    DNSServiceErrorType DNSServiceSetDispatchQueue(
                            DNSServiceRef    service,
                            dispatch_queue_t queue);

The DNSServiceRef can be associated with a shared connection or with a per function connection.

See below for an example of its use.

7.0 Creating A DNSServiceRef For A Shared Connection

The only way to create a DNSServiceRef for a connection which can be shared is by using the function
DNSServiceCreateConnection which is declared like this

   DNSServiceErrorType DNSServiceCreateConnection(DNSServiceRef* sdRef);

A copy of the initialized DNSServiceRef that results should be passed to each function that is going to share the connection.

See below for an example of its use.

8.0 DNSServiceBrowse In Action

This is the start method of the third version of the FindServices class.

    - (BOOL)start
    {
        DNSServiceErrorType error = DNSServiceCreateConnection(&dnsServiceRef);
    
        if (error != kDNSServiceErr_NoError)
        {
            NSLog(@"Error: DNSServiceCreateConnection %d", error);
            return NO;
        }
        error = DNSServiceSetDispatchQueue(dnsServiceRef, dispatch_get_main_queue());
        if (error != kDNSServiceErr_NoError)
        {
            NSLog(@"Error: DNSServiceSetDispatchQueue %d", error);
            return NO;
        }
        browseRef = dnsServiceRef;
        error = DNSServiceBrowse(
                    &browseRef,
                    kDNSServiceFlagsShareConnection,
                    kDNSServiceInterfaceIndexAny,
                    [self.type UTF8String],
                    [self.domain UTF8String],
                    browseCallback,
                    (__bridge void*)self);
        if (error != kDNSServiceErr_NoError)
        {
            NSLog(@"Error: DNSServiceBrowse %d", error);
            return NO;
        }
        return YES;
    }
    static void browseCallback(
                    DNSServiceRef       sdRef,
                    DNSServiceFlags     theFlags,
                    uint32_t            theInterfaceIndex,
                    DNSServiceErrorType theErrorCode,
                    const char*         theName,
                    const char*         theType,
                    const char*         theDomain,
                    void*               theContext)
    {
        NSLog(@"browseCallback:  error == %d flags == %s", theErrorCode, flagsToString(theFlags));
        
        if (theErrorCode == kDNSServiceErr_NoError)
        {
            ServiceIdentifier si = { theName, theType, theDomain };
        
            if ((theFlags & kDNSServiceFlagsAdd) != 0)
            {
                [(__bridge FindServices*)theContext serviceFound:&si onInterface:theInterfaceIndex];
            }
            else
            {
                [(__bridge FindServices*)theContext serviceLost:&si];
            }
        }
        else
        {
            [(__bridge FindServices*)theContext browseFailed:theErrorCode];
        }
    }

9.0 DNSServiceResolve In Action

This is the resolve:onInterface: method of the ServiceResolver class

    - (void)resolve:(ServiceIdentifier*)theServiceId onInterface:(uint32_t)theInterfaceIndex
    {
        DNSServiceErrorType error;
        
        error = DNSServiceResolve(
                    &resolveRef,
                    kDNSServiceFlagsShareConnection,
                    theInterfaceIndex,
                    theServiceId->name,
                    theServiceId->type,
                    theServiceId->domain,
                    resolveCallback,
                    (__bridge void*)self);
        if (error != kDNSServiceErr_NoError)
        {
            NSLog(@"DNSServiceResolve: %d", error);
            [self.delegate serviceResolver:self didFail:error];
        }
    }

and this is the associated callback function.

    static void resolveCallback(
                    DNSServiceRef        theRef,
                    DNSServiceFlags      theFlags,
                    uint32_t             theInterfaceIndex,
                    DNSServiceErrorType  theErrorCode,
                    const char*          theFullName,
                    const char*          theTarget,
                    uint16_t             thePort,
                    uint16_t             theTXTRecordLength,
                    const unsigned char* theTXTRecord,
                    void*                theContext)
    {
        NSLog(@"resolveCallback: error == %d flags == %s", theErrorCode, flagsToString(theFlags));
        
        if (theErrorCode != kDNSServiceErr_NoError)
        {
            NSLog(@"resolveCallback: error !");
            [(__bridge ServiceResolver*)theContext resolveFailed:theErrorCode];
        }
        else
        if (theFlags == 0)
        {
            ServiceInfo si =
                {
                    theFullName,
                    theTarget,
                    ntohs(thePort),
                    theTXTRecordLength,
                    theTXTRecord
                };
        
            NSLog(@"%s %s %u", theFullName, theTarget, thePort);
        
            [(__bridge ServiceResolver*)theContext resolved:&si onInterface:theInterfaceIndex];
        }
        else
        {
            NSLog(@"resolveCallback: flags set !");
            [(__bridge ServiceResolver*)theContext internalError];
        }
    }

10.0 DNSServiceGetAddrInfo In Action

This is the resolved:onInterface: method of the ServiceResolver class

    - (void)resolved:(const ServiceInfo*)theServiceInfo onInterface:(uint32_t)theInterfaceIndex
    {
        DNSServiceErrorType error;
        
        error = DNSServiceGetAddrInfo(
                    &addressRef,
                    kDNSServiceFlagsShareConnection,
                    theInterfaceIndex,
                    kDNSServiceProtocol_IPv4|kDNSServiceProtocol_IPv6,
                    theServiceInfo->target,
                    addressInfoCallback,
                    (__bridge void*)self);
        if (error == kDNSServiceErr_NoError)
        {
            [self.builder serviceInfo:theServiceInfo];
        }
        else
        {
            NSLog(@"DNSServiceGetAddrInfo: %d", error);
            [self.delegate serviceResolver:self didFail:error];
        }
    }

and this is the associated callback function.

    static void addressInfoCallback(
                    DNSServiceRef          theServiceRef,
                    DNSServiceFlags        theFlags,
                    uint32_t               theInterfaceIndex,
                    DNSServiceErrorType    theErrorCode,
                    const char*            theHostname,
                    const struct sockaddr* theAddress,
                    uint32_t               theTTL,
                    void*                  theContext)
    {
        NSLog(@"addressInfoCallback: error == %d flags == %s ", theErrorCode, flagsToString(theFlags));
        
        if (theErrorCode != kDNSServiceErr_NoError)
        {
            NSLog(@"addressInfoCallback error");
            [(__bridge ServiceResolver*)theContext getAddrInfoFailed:theErrorCode];
        }
        else
        if ((theFlags & kDNSServiceFlagsAdd) != 0)
        {
            NSLog(@"theHostname == %s", theHostname);
            NSLog(@"theAddress->sa_family == %d", theAddress->sa_family);
        
            [(__bridge ServiceResolver*)theContext address:theAddress];
            if ((theFlags & kDNSServiceFlagsMoreComing) == 0)
            {
                [(__bridge ServiceResolver*)theContext done];
            }
        }
        else
        {
            NSLog(@"theHostname == %s", theHostname);
            NSLog(@"theAddress->sa_family == %d", theAddress->sa_family);
            // ignore
        }
    }

11.0 Examples

In each case FindServices is looking for services of type

    "_ipp._tcp."

in the domain

    "local."

In each case the log output is from FindServices and its delegate running on an iPad running iOS 7.0.

7.1 A Single IPPServer

A single instance of the CUPS test server IPPServer with the name ipp_server_1
running on a Mac and then being stopped.

In this case the addressInfoCallback function is called twice, first with the IPv6 address then with the IPv4 address.

    ...
        
    2013-11-18 14:53:20.304 XperTakeThree[334:60b] browseCallback:  error == 0 flags == kDNSServiceFlagsAdd
    2013-11-18 14:53:20.307 XperTakeThree[334:60b] serviceFound: ipp_server_1._ipp._tcp.local.
    2013-11-18 14:53:20.309 XperTakeThree[334:60b] resolveCallback: error == 0 flags == <none>
    2013-11-18 14:53:20.310 XperTakeThree[334:60b] ipp_server_1._ipp._tcp.local. Simons-Computer.local. 56088
    2013-11-18 14:53:20.312 XperTakeThree[334:60b] addressInfoCallback: error == 0 flags == kDNSServiceFlags{Add,MoreComing}
    2013-11-18 14:53:20.313 XperTakeThree[334:60b] theHostname == Simons-Computer.local.
    2013-11-18 14:53:20.314 XperTakeThree[334:60b] theAddress->sa_family == 30
    2013-11-18 14:53:20.315 XperTakeThree[334:60b] addressInfoCallback: error == 0 flags == kDNSServiceFlagsAdd
    2013-11-18 14:53:20.316 XperTakeThree[334:60b] theHostname == Simons-Computer.local.
    2013-11-18 14:53:20.317 XperTakeThree[334:60b] theAddress->sa_family == 2
    2013-11-18 14:54:18.545 XperTakeThree[334:60b] browseCallback:  error == 0 flags == <none>
    2013-11-18 14:54:18.547 XperTakeThree[334:60b] serviceLost: name == ipp_server_1._ipp._tcp.local.
        
    ...

11.2 A Single Printer

A printer being turned on and then turned off a couple of minutes later.

In this case we only get a single address, the IPV4 one, but we do get a second call to the function addressInfoCallback
function when the printer is turned off

    ...
        
    2013-11-18 14:55:55.137 XperFS_DNS_SD[351:60b] browseCallback:  error == 0 flags == kDNSServiceFlagsAdd
    2013-11-18 14:55:55.140 XperFS_DNS_SD[351:60b] serviceFound: Canon MG6200 series._ipp._tcp.local.
    2013-11-18 14:55:55.141 XperFS_DNS_SD[351:60b] resolveCallback: error == 0 flags == <none>
    2013-11-18 14:55:55.142 XperFS_DNS_SD[351:60b] Canon32MG620032series._ipp._tcp.local. 7D300C000000.local. 30466
    2013-11-18 14:55:55.144 XperFS_DNS_SD[351:60b] addressInfoCallback: error == 0 flags == kDNSServiceFlagsAdd
    2013-11-18 14:55:55.145 XperFS_DNS_SD[351:60b] theHostname == 7D300C000000.local.
    2013-11-18 14:55:55.146 XperFS_DNS_SD[351:60b] theAddress->sa_family == 2
    2013-11-18 15:02:18.835 XperFS_DNS_SD[351:60b] addressInfoCallback: error == 0 flags == <none>
    2013-11-18 15:02:18.837 XperFS_DNS_SD[351:60b] theHostname == 7D300C000000.local.
    2013-11-18 15:02:18.839 XperFS_DNS_SD[351:60b] theAddress->sa_family == 2
    2013-11-18 15:02:19.936 XperFS_DNS_SD[351:60b] browseCallback:  error == 0 flags == <none>
    2013-11-18 15:02:19.938 XperFS_DNS_SD[351:60b] serviceLost: name == Canon MG6200 series._ipp._tcp.local.

    ...

Notes

  • Subject to terms and conditions. The number of file descriptors may be subject to limits.

Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

November 14, 2013

Service Discovery In Android And iOS: Part Six – iOS Take Two

At the Core Foundation level we have the CFNetServices API which supports the registration and discovery of services using DNS/mDNS.

1.0 CFNetServiceBrowser

A CFNetServiceBrowser is the CFNetServices equivalent of an NSNetServiceBrowser.

2.0 CFNetService

A CFNetService is the CFNetServices equivalent of an NSNetService.

3.0 Synchronous vs. Aynchronous

Unlike the NSNetServiceBrowser and NSNetService methods the equivalent CFNetServiceBrowser and CFNetService functions can be used synchronously or asynchronously.

By default the functions are synchronous.

To make them asynchronous for a given CFNetServiceBrowser or CFNetService it must be added to a CFRunLoop.

4.0 Searching For Services Asynchronously

To search for services of a given type using the CFNetworkServices API we need to

  1. create a CFNetServiceBrowser

  2. make it asynchronous

  3. start the search

4.1 CFNetServiceBrowserCreate

We can create a CFNetServiceBrowser using the function CFNetServiceBrowserCreate which is declared like this

    CFNetServiceBrowserRef CFNetServiceBrowserCreate (
                               CFAllocatorRef                    alloc,
                               CFNetServiceBrowserClientCallBack clientCB,
                               CFNetServiceClientContext*        clientContext);

The alloc argument is a reference to an allocator to use when creating the CFNetServiceBrowser or more likely the constant

    kCFAllocatorDefault

4.1.1 The clientCB Argument

The clientCB argument is a pointer to a function of type CFNetServiceBrowserClientCallBack.

This function will be invoked when a service is found or if an error occurs.

The function type CFNetServiceBrowserClientCallBack is declared like this

    typedef void (*CFNetServiceBrowserClientCallBack) (
                       CFNetServiceBrowserRef browser,
                       CFOptionFlags          flags,
                       CFTypeRef              domainOrService,
                       CFStreamError*         error,
                       void*                  info);;

The browser argument is the CFNetServiceBrowserRef that was returned from the call to CFNetServiceBrowserCreate.

The callback function is also invoked when searching for domains so the flags argument is used to distinguish between the two uses.

It is also used to distinguish between the discovery of a service and the disappearance of a previously discovered service.

When a service is discovered the value of the flags argument will be zero (0).

When a previously discovered service disappears the value of the flags argument will be

   kCFNetServiceFlagRemove

When being invoked on the discovery or disappearance of a service the domainOrService argument will be a
CFNetServiceRef.

If an error has occurred, the error and domain fields of error argument will be set.

The info argument is the value of the info field of the CFNetServiceClientContext passed to the call to CFNetServiceBrowserCreate.

4.1.2 The clientContext Argument

The clientContext argument is a pointer to a CFNetServiceClientContext which is declared like this.

    struct CFNetServiceClientContext {
        CFIndex                            version;
        void*                              info;
        CFAllocatorRetainCallBack          retain;
        CFAllocatorReleaseCallBack         release;
        CFAllocatorCopyDescriptionCallBack copyDescription;
    };
        
    typedef struct CFNetServiceClientContext CFNetServiceClientContext;

The info field can be used to store a pointer to an ‘object’ which will be passed to the callback function passed via the clientCB argument.

If the retain and release fields are not NULL then the functions specified will be invoked when the implementation wishes to retain and release the ‘object’ specified in the info field.

It is not clear from the documentation whether the contents of the CFNetServiceClientContext are copied.

A const qualifier is sometimes a clue, but a little experimentation shows that they are, so it is safe to stack allocate.

4.2 CFNetServiceBrowserScheduleWithRunLoop

We can add our newly created CFNetServiceBrowser to a CFRunLoop using the function CFNetServiceBrowserScheduleWithRunLoop which is declared like this

    void CFNetServiceBrowserScheduleWithRunLoop(
             CFNetServiceBrowserRef browser,
             CFRunLoopRef           runLoop,
             CFStringRef            runLoopMode);

The easiest way to use this is to add the CFNetServiceBrowser to the main CFRunLoop in the default mode like so

    CFNetServiceBrowserScheduleWithRunLoop(
        browser, 
        CFRunLoopGetMain(), 
        kCFRunLoopDefaultMode);

4.3 CFNetServiceBrowserSearchForServices

Once we have made our CFNetServiceBrowse asynchronous we can start the search for services by calling the function CFNetServiceBrowserSearchForServices which is declared like this

    Boolean CFNetServiceBrowserSearchForServices (
                CFNetServiceBrowserRef browser,
                CFStringRef            domain,
                CFStringRef            serviceType,
                CFStreamError*         error);

The browser argument should be the CFNetServiceBrowserRef returned from the call to CFNetServiceBrowserCreate.

The domain argument should be the absolute name of the domain in which to search, e.g.,

    "local."

The serviceType argument should be the domain relative type of the services to search for, e.g.,

    "_ipp._tcp."

The documentation for the error argument is a tad confusing.

It states

A pointer to a CFStreamError structure, that, if an error occurs, will be set to the error and the error’s domain and passed to your callback function.

The

… and passed to your callback

bit does not appear to be true.

If it is not possible to start the search then the function returns false immediately and the domain and error fields of the CFStreamError are set.

5.0 Resolving A Service Asynchronously

Once a service has been found we need to resolve it …

To do this asynchronously we need to

  1. make it possible to get the result asynchronously

  2. make the CFNetService asynchronous

  3. start the resolution

5.1 CFNetServiceSetClient

To get the results from CFNetService functions when running asynchronously we must associate a callback function and a context with the CFNetService first.

We do this using the function CFNetServiceSetClient which is declared like this

    Boolean CFNetServiceSetClient(
                CFNetServiceRef            theService,
                CFNetServiceClientCallBack clientCB,
                CFNetServiceClientContext* clientContext);

5.1.1 The clientCB Argument

The clientCB argument is a pointer to a function of type CFNetServiceClientCallBack

This function will be invoked when the service is resolved or an error occurs.

The function type CFNetServiceClientCallBack is declared like this

    typedef void (*CFNetServiceClientCallBack) (
                      CFNetServiceRef theService,
                      CFStreamError*  error,
                      void*           info);

The info argument is the value of the info field of the CFNetServiceClientContext passed as the clientContext argument in the call to the CFNetServiceSetClient

If an error has occurred, the error and domain fields of error argument will be set.

5.1.2 The clientContext Argument

The clientContext argument is a pointer to a CFNetServiceClientContext which we have already seen used with the function CFNetServiceBrowserCreate.

5.2 CFNetServiceScheduleWithRunLoop

We can add our CFNetService instance to a CFRunLoop using the function CFNetServiceScheduleWithRunLoop which is declared like this.

    void CFNetServiceScheduleWithRunLoop(
             CFNetServiceRef theService,
             CFRunLoopRef    runLoop,
             CFStringRef     runLoopMode);

The easiest way to use this is to add the CFNetService to the main CFRunLoop in the default mode like so

    CFNetServiceScheduleWithRunLoop(service, CFRunLoopGetMain(), kCFRunLoopDefaultMode);

5.3 CFNetServiceResolveWithTimeout

Once we have made our CFNetService asynchronous we can start the resolution bey calling the function
CFNetServiceResolveWithTimeout which is declared like this

    Boolean CFNetServiceResolveWithTimeout(
                CFNetServiceRef theService,
                CFTimeInterval  timeout,
                CFStreamError*  error);

The timeout argument specifies the amount of time in seconds that the implementation should wait for the resolution to complete If the value is less than or equal to zero the implementation will wait indefinitely.

If it not possible to start the resolution the function returns false immediately and the domain and error fields of the CFStreamError argument are set.

6.0 The FindServices Class

Here is the FindServices class re-written to use the CFNetServices API.

    //
    //  FindServices.m
    //  XperTakeTwo
    //
    //  Created by Simon Lewis on 12/11/2013.
    //  Copyright (c) 2013 Simon Lewis. All rights reserved.
    //
    
    #import "Service.h"
    
    #import "FindServices.h"
    
    @interface FindServices ()
    
    @property NSString*             type;
    @property NSString*             domain;
    
    @property NSMutableDictionary*  services;
    
    
    - (void)serviceFound:(CFNetServiceRef)theService;
    
    - (void)serviceLost:(CFNetServiceRef)theService;
    
    
    - (void)resolved:(CFNetServiceRef)theService;
    
    - (void)resolveFailed:(CFNetServiceRef)theService withError:(CFStreamError*)theError;
    
    
    - (void)stopBrowser;
    
    - (void)stopService:(CFNetServiceRef)theService;
    
    - (void)log:(NSString*)theMessage service:(CFNetServiceRef)theService;
    
    @end
    
    @implementation FindServices
    {
        CFNetServiceBrowserRef      browser;
    }
    
    - (FindServices*)initWithType:(NSString*)theType andDomain:(NSString*)theDomain
    {
        self = [super init];
        if (self != nil)
        {
            self.type     = theType;
            self.domain   = theDomain;
            self.services = [NSMutableDictionary dictionaryWithCapacity:8];
        }
        return self;
    }
    
    
    
    static void browserCallBack(
                    CFNetServiceBrowserRef  theBrowser,
                    CFOptionFlags           theFlags,
                    CFTypeRef               theDomainOrService,
                    CFStreamError*          theError,
                    void*                   theInfo)
    {
        NSLog(@"browserCallBack");
    
        if ((theError->error) != 0)
        {
            NSLog(@"error: %d\n", (int)theError->error);
        }
        else
        if ((theFlags & kCFNetServiceFlagIsDomain) != 0)
        {
            NSLog(@"domain !\n");
        }
        else // service
        if ((theFlags & kCFNetServiceFlagRemove) == 0)
        {
            [(__bridge FindServices*)theInfo serviceFound:(CFNetServiceRef)theDomainOrService];
        }
        else
        {
            [(__bridge FindServices*)theInfo serviceLost:(CFNetServiceRef)theDomainOrService];
        }
    }
    
    - (void)start
    {
        CFNetServiceClientContext   context;
    
        memset(&context, 0, sizeof(context));
        context.info = (__bridge void *)(self);
    
        browser = CFNetServiceBrowserCreate(kCFAllocatorDefault, browserCallBack, &context);
    
        CFNetServiceBrowserScheduleWithRunLoop(browser, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
    
        Boolean       status;
        CFStreamError error;
    
        status = CFNetServiceBrowserSearchForServices(
                     browser,
                     (__bridge CFStringRef)self.domain,
                     (__bridge CFStringRef)self.type,
                     &error);
        if (status == 0)
        {
            NSLog(@"error.error == %d\n", (int)error.error);
            [self stopBrowser];
        }
    }

    static void resolveCallBack(
                    CFNetServiceRef theService,
                    CFStreamError*  theError,
                    void*           theInfo)
    {
        NSLog(@"resolveCallback");

        if (theError->error == 0)
        {
            [(__bridge FindServices*)theInfo resolved:theService];
        }
        else
        {
            [(__bridge FindServices*)theInfo resolveFailed:theService withError:theError];
        }
    }
    
    - (void)serviceFound:(CFNetServiceRef)theService
    {
        [self log:@"service found: %@.%@%@" service:theService];
    
        CFNetServiceClientContext   context;
    
        memset(&context, 0, sizeof(context));
        context.info = (__bridge void *)(self);
    
        CFNetServiceSetClient(theService, resolveCallBack, &context);
    
        CFNetServiceScheduleWithRunLoop(theService, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
    
        Boolean       status;
        CFStreamError error;
    
        status = CFNetServiceResolveWithTimeout(theService, 0.0, &error);
        if (status == 0)
        {
            NSLog(@"error.error == %d\n", (int)error.error);
    
           [self stopService:theService];
        }
    }
    
    - (void)serviceLost:(CFNetServiceRef)theService
    {
        [self log: @"service lost: %@.%@%@" service:theService];
    
        NSString* name   = [NSString stringWithFormat:
                                @"%@.%@%@",
                                CFNetServiceGetName(
                                    theService),
                                CFNetServiceGetType(
                                    theService),
                                CFNetServiceGetDomain(
                                    theService)];
        Service* service = [self.services objectForKey:name];
    
        if (service != nil)
        {
            [service lost];
            [self.services removeObjectForKey:name];
            [self.delegate findServices:self didLoseService:service];
        }
        else
        {
            [self log: @"service lost but was not found: %@.%@%@" service:theService];
        }
    }
    
    - (void)resolved:(CFNetServiceRef)theService
    {
        [self log:@"service resolved: %@.%@%@" service:theService];
    
        CFArrayRef addresses = CFNetServiceGetAddressing(theService);
    
        if (CFArrayGetCount(addresses) != 0)
        {
            Service* service = [[Service alloc] init:theService];
    
            [self.services setObject:service forKey:service.name];
            [self.delegate findServices:self didFindService:service];
        }
        else
        {
            NSLog(@"service has 0 addresses: lost ?");
        }
    }
    
    - (void)resolveFailed:(CFNetServiceRef)theService withError:(CFStreamError *)theError
    {
        [self log:@"service resolvedFailed: %@.%@%@" service:theService];
        [self stopService:theService];
    }
    
    - (void)stopBrowser
    {
        CFNetServiceBrowserUnscheduleFromRunLoop(browser, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
        CFNetServiceBrowserInvalidate(browser);
        CFNetServiceBrowserStopSearch(browser, NULL);
    }
    
    - (void)stopService:(CFNetServiceRef)theService
    {
        CFNetServiceClientContext   context;
    
        memset(&context, 0, sizeof(context));
    
        CFNetServiceUnscheduleFromRunLoop(theService, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
        CFNetServiceSetClient(theService, NULL, &context);
        CFNetServiceCancel(theService);
    }
    
    - (void)log:(NSString*)theMessage service:(CFNetServiceRef)theService
    {
        NSLog(
            theMessage,
            CFNetServiceGetName(
                theService),
            CFNetServiceGetType(
                theService),
           CFNetServiceGetDomain(
               theService));
    }
    
    @end

7.0 Examples

In each case FindServices is looking for services of type

    "_ipp._tcp."

in the domain

    "local."

In each case the log output is from FindServices and its delegate running on an iPad running iOS 7.0.

7.1 A Single IPPServer

A single instance of the CUPS test server IPPServer with the name ipp_server_1 running on a Mac and then being stopped.

    ...

    2013-11-14 14:07:07.561 XperTakeTwo[665:60b] browserCallBack
    2013-11-14 14:07:07.564 XperTakeTwo[665:60b] service found: ipp_server_1._ipp._tcp.local.
    2013-11-14 14:07:07.593 XperTakeTwo[665:60b] resolveCallback
    2013-11-14 14:07:07.595 XperTakeTwo[665:60b] service resolved: ipp_server_1._ipp._tcp.local.
    2013-11-14 14:07:07.597 XperTakeTwo[665:60b] findServices:didFindService:<Service: 0x14e86990>
    2013-11-14 14:07:13.931 XperTakeTwo[665:60b] browserCallBack
    2013-11-14 14:07:13.933 XperTakeTwo[665:60b] service lost: ipp_server_1._ipp._tcp.local.
    2013-11-14 14:07:13.935 XperTakeTwo[665:60b] findServices:didLoseService::<Service: 0x14e86990>

    ...

7.2 A Single Printer

A printer being turned on and then turned a couple of minutes later.

Note the lines shown in bold for emphasis.

When the printer is turned off the resolveCallback function is being called for a second time but this time the CFNetService has no addresses.

This is the same thing that happened in this case when using the NSNetServiceBrowser/NSNetService API. (see here)

    ...

    2013-11-14 14:07:55.177 XperTakeTwo[671:60b] browserCallBack
    2013-11-14 14:07:55.180 XperTakeTwo[671:60b] service found: Canon MG6200 series._ipp._tcp.local.
    2013-11-14 14:07:55.250 XperTakeTwo[671:60b] resolveCallback
    2013-11-14 14:07:55.252 XperTakeTwo[671:60b] service resolved: Canon MG6200 series._ipp._tcp.local.
    2013-11-14 14:07:55.255 XperTakeTwo[671:60b] findServices:didFindService:<Service: 0x1452e060>

    2013-11-14 14:09:05.838 XperTakeTwo[671:60b] resolveCallback
    2013-11-14 14:09:05.840 XperTakeTwo[671:60b] service resolved: Canon MG6200 series._ipp._tcp.local.
    2013-11-14 14:09:05.843 XperTakeTwo[671:60b] service has 0 addresses: lost ?

    2013-11-14 14:09:06.910 XperTakeTwo[671:60b] browserCallBack
    2013-11-14 14:09:06.912 XperTakeTwo[671:60b] service lost: Canon MG6200 series._ipp._tcp.local.
    2013-11-14 14:09:06.915 XperTakeTwo[671:60b] findServices:didLoseService::<Service: 0x1452e060>

    ...

Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

November 12, 2013

Service Discovery In Android And iOS: Part Five – iOS Take One

When it comes to iOS we are spoilt for choice. There are no less than three APIs available for service discovery.

Starting at the Foundation level we have the Objective-C class NSNetServiceBrowser.

1.0 Instance Creation

The NSNetServiceBrowser class defines a single no argument init method so to create one we simply do this

    browser = [[NSNetServiceBrowser alloc] init];

2.0 Starting A Search

The search for services of a given type is asynchronous.

To start the search we call the method

    - (void)searchForServicesOfType:(NSString*)type inDomain:(NSString*)domainString;

The type argument should be the domain relative name of the service type to search for, e.g.,

    "_ipp._tcp."

Note the dot (‘.’) at the end.

The domainString should be the absolute name of the domain to search, e.g.,

    "local."

Note the dot (‘.’) at the end.

Once the search has started it will continue indefinitely unless it is explicitly stopped.

3.0 NSNetServiceBrowserDelegate

NSNetServiceBrowser uses the standard delegate pattern to return its results.

The delegate is required to implement the NSNetServiceBrowserDelegate protocol.

3.1 netServiceBrowserWillSearch:

Following the call to the method searchForServicesOfType:inDomain: if the NSNetServiceBrowser instance is going to perform the search it calls the delegate’s implementation of the method

    - (void)netServiceBrowserWillSearch:(NSNetServiceBrowser*)netServiceBrowser

3.2 netServiceBrowser:didNotSearch:

Following the call to the method searchForServicesOfType:inDomain: if the NSNetServiceBrowser instance is not going to perform the search it calls the delegate’s implementation of the method

    - (void)netServiceBrowser:(NSNetServiceBrowser*)netServiceBrowser didNotSearch:(NSDictionary*)errorInfo

The easiest way to see this method in action is to get the type name wrong in the call to searchForServicesOfType:inDomain:, e.g.,

    "._ipp.tcp."

in which case the NSDictionary passed as the errorInfo argument will look like this

    {
        NSNetServicesErrorCode   = "-72004";
        NSNetServicesErrorDomain = 10;
    }

You can find the error codes in NSNetServices.h.

3.3 netServiceBrowser:didFindService:moreComing:

Following the call to the method searchForServicesOfType:inDomain: if the NSNetServiceBrowser instance finds a service of the given type it calls the delegate’s implementation of the method

    - (void)netServiceBrowser:
                (NSNetServiceBrowser*)netServiceBrowser
            didFindService:
                (NSNetService*)netService
            moreComing:
                (BOOL)moreServicesComing

3.4 netServiceBrowser:didRemoveService:moreComing:

If a service that has previously been found is no longer available the NSNetServiceBrowser instance calls the delegate’s implementation of the method

    - (void)netServiceBrowser:
                (NSNetServiceBrowser*)netServiceBrowser
            didRemoveService:
                (NSNetService*)netService
            moreComing:
                (BOOL)moreServicesComing

4.0 NSNetService

As discovered, the service as represented by the NSNetService instance is still in a nascent state. Neither its address nor the key/value pairs in its TXT record are available.

To be useful it has to be resolved.

The resolution of a service is performed asynchronously. It is started by invoking the NSNetService method resolveWithTimeout: which is declared like this

    - (void)resolveWithTimeout:(NSTimeInterval)timeout

Once started the resolution of a service will either complete successfully ot time out after the interval specified by the timeout argument.

5.0 NSNetServiceDelegate

The success or failure of the resolution of a NSNetService instance is reported to the delegate of that instance.

The delegate must implement the NSNetServiceDelegate protocol.

5.1 netServiceWillResolve:

Following the call to the resolveWithTimeout: method the NSNetService instance will call its delegate’s implementation of the method

    - (void)netServiceWillResolve:(NSNetService*)sender

5.2 netService:didNotResolve:

If the resolution of the service fails the NSNetService instance calls its delegate’s implementation of the method

    - (void)netService:(NSNetService *)sender didNotResolve:(NSDictionary *)errorDict

5.3 netServiceDidResolveAddress:

If the resolution of the service succeeds the NSNetService instance calls its delegate’s implementation of the method

    - (void)netServiceDidResolveAddress:(NSNetService*)sender;t

There is a caveat however. As we shall see ‘success’ in this context does not always mean what you might expect.

6.0 The FindServices Class

To make things slightly simpler we can wrap up the classes and their delegates in a single class FindServices
as we did in the Java case.

FindServicesDelegate.h

    //
    //  FindServicesDelegate.h
    //  XperTakeOne
    //
    //  Created by Simon Lewis on 03/11/2013.
    //  Copyright (c) 2013 Simon Lewis. All rights reserved.
    //
        
    #import <Foundation/Foundation.h>
        
    @class FindServices;
    @class Service;
        
    @protocol FindServicesDelegate <NSObject>
        
    - (void)findServices:(FindServices*)theFindServices didFindService:(Service*)theService;
        
    - (void)findServices:(FindServices*)theFindServices didLoseService:(Service*)theService;
        
    @end

FindServices.h

    //
    //  FindServices.h
    //  XperTakeOne
    //
    //  Created by Simon Lewis on 03/11/2013.
    //  Copyright (c) 2013 Simon Lewis. All rights reserved.
    //
        
    #import <Foundation/Foundation.h>
        
    #import "FindServicesDelegate.h"
        
    @interface FindServices : NSObject<NSNetServiceBrowserDelegate, NSNetServiceDelegate>
        
    @property (weak) id<FindServicesDelegate>   delegate;
        
    - (FindServices*)initWithType:(NSString*)theType andDomain:(NSString*)theDomain;
        
    - (void)start;
        
    @end

FindServices.m

    //
    //  FindServices.m
    //  XperTakeOne
    //
    //  Created by Simon Lewis on 03/11/2013.
    //  Copyright (c) 2013 Simon Lewis. All rights reserved.
    //
        
    #import "Service.h"
        
    #import "FindServices.h"
        
    @interface FindServices ()
        
    @property NSString*             type;
    @property NSString*             domain;
    @property NSNetServiceBrowser*  browser;
    @property NSMutableArray*       resolving;
    @property NSMutableDictionary*  services;
        
    @end
        
    @implementation FindServices
        
    - (FindServices*)initWithType:(NSString*)theType andDomain:(NSString*)theDomain
    {
        self = [super init];
        if (self != nil)
        {
            self.type      = theType;
            self.domain    = theDomain;
            self.browser   = [[NSNetServiceBrowser alloc] init];
            self.resolving = [NSMutableArray arrayWithCapacity:8];
            self.services  = [NSMutableDictionary dictionaryWithCapacity:8];
        
            self.browser.delegate = self;
        }
        return self;
    }
        
    - (void)start
    {
        [self.browser searchForServicesOfType:self.type inDomain:self.domain];
    }
        
    // NSNetServiceBrowserDelegate
        
    - (void)netServiceBrowserWillSearch:(NSNetServiceBrowser *)theBrowser
    {
        NSLog(@"netServiceBrowserWillSearch:\n");
    }
        
    - (void)netServiceBrowser:(NSNetServiceBrowser *)theBrowser didNotSearch:(NSDictionary *)theErrors
    {
        NSLog(@"netServiceBrowser:didNotSearch: %@", theErrors);
    }
        
    - (void)netServiceBrowser:
                (NSNetServiceBrowser *)aNetServiceBrowser
            didFindService:
                (NSNetService *)theService
            moreComing:
                (BOOL)moreComing
    {
        NSLog(@"netServiceBrowser:didFindService: %@", theService);
        
        [self.resolving addObject:theService];
        theService.delegate = self;
        [theService resolveWithTimeout:0.0];
    }
        
    - (void)netServiceBrowser:
                (NSNetServiceBrowser *)aNetServiceBrowser
            didRemoveService:
                (NSNetService *)theService
            moreComing:
                (BOOL)moreComing
    {
        NSLog(@"netServiceBrowser:didRemoveService: %@", theService);
        
        Service* service = [self.services objectForKey:theService.name];
        
        if (service != nil)
        {
            [self.services removeObjectForKey:theService.name];
            [self.delegate findServices:self didLoseService:service];
        }
        else
        {
            NSLog(@"%@ removed without being found ?", theService.name);
        }
    }
        
    // NSNetServiceDelegate
        
    - (void)netServiceWillResolve:(NSNetService *)theService
    {
        NSLog(@"netServiceWillResolve");
    }
        
    - (void)netServiceDidResolveAddress:(NSNetService *)theService
    {
        NSUInteger nAddresses = [[theService addresses] count];
        
        NSLog(@"netServiceDidResolveAddress: %@ nAddresses == %lu", theService, (unsigned long)nAddresses);
        
        if (nAddresses != 0)
        {
            Service* service = [[Service alloc] init:theService];
        
            [self.resolving removeObject:theService];
            [self.services setObject:service forKey:theService.name];
            [self.delegate findServices:self didFindService:service];
        }
        else
        {
            Service* service = [self.services objectForKey:theService.name];
        
            if (service != nil)
            {
                NSLog(@"service %@ now has 0 addresses !", theService.name);
            }
            else
            {
                NSLog(@"resolve failed ? %@ has 0 addresses", theService.name);
            }
        }
    }
        
    - (void)netService:(NSNetService *)theService didNotResolve:(NSDictionary *)theErrors
    {
        NSLog(@"netServiced:didNotResolve: %@ %@", theService, theErrors);
        
        [self.resolving removeObject:theService];
    }
        
    @end

7.0 Examples

In each case FindServices is looking for services of type

    "_ipp._tcp."

in the domain

    "local."

In each case the log output is from FindServices and its delegate running on an iPad running iOS 7.0.

7.1 A Single IPPServer

A single instance of the CUPS test server IPPServer with the name ipp_server_1 running on a Mac and then being stopped.

    ...

    2013-11-12 08:26:05.516 XperTakeOne[163:60b] netServiceBrowserWillSearch:
    2013-11-12 08:26:12.500 XperTakeOne[163:60b] netServiceBrowser:didFindService: \
        <NSNetService 0x1464bd60> local. _ipp._tcp. ipp_server_1
    2013-11-12 08:26:12.504 XperTakeOne[163:60b] netServiceWillResolve
    2013-11-12 08:26:12.533 XperTakeOne[163:60b] netServiceDidResolveAddress: \
        <NSNetService 0x1464bd60> local. _ipp._tcp. ipp_server_1 nAddresses == 2
    2013-11-12 08:26:12.535 XperTakeOne[163:60b] findServices:didFindService: <Service: 0x14631890>
    2013-11-12 08:27:56.204 XperTakeOne[163:60b] netServiceBrowser:didRemoveService: \
        <NSNetService 0x14522f50> local. _ipp._tcp. ipp_server_1
    2013-11-12 08:27:56.207 XperTakeOne[163:60b] findServices:didLoseService: <Service: 0x14631890>

    ...

7.2 Two IPPServers

Two instances of the CUPS test server IPPServer with the names ipp_server_1 and ipp_server_2 running on a Mac and then being stopped.

    ...

    2013-11-12 08:29:54.404 XperTakeOne[171:60b] netServiceBrowserWillSearch:
    2013-11-12 08:29:54.525 XperTakeOne[171:60b] netServiceBrowser:didFindService: \
        <NSNetService 0x1757ac10> local. _ipp._tcp. ipp_server_1
    2013-11-12 08:29:54.528 XperTakeOne[171:60b] netServiceWillResolve
    2013-11-12 08:29:54.531 XperTakeOne[171:60b] netServiceBrowser:didFindService: \
        <NSNetService 0x17578140> local. _ipp._tcp. ipp_server_2
    2013-11-12 08:29:54.533 XperTakeOne[171:60b] netServiceWillResolve
    2013-11-12 08:29:55.553 XperTakeOne[171:60b] netServiceDidResolveAddress:\
        <NSNetService 0x17578140> local. _ipp._tcp. ipp_server_2 nAddresses == 2
    2013-11-12 08:29:55.556 XperTakeOne[171:60b] findServices:didFindService: \
        <Service: 0x17673570>
    2013-11-12 08:29:55.558 XperTakeOne[171:60b] netServiceDidResolveAddress: \
        <NSNetService 0x1757ac10> local. _ipp._tcp. ipp_server_1 nAddresses == 2
    2013-11-12 08:29:55.559 XperTakeOne[171:60b] findServices:didFindService: <Service: 0x176b25f0>
    2013-11-12 08:30:57.454 XperTakeOne[171:60b] netServiceBrowser:didRemoveService: \
        <NSNetService 0x1757e7d0> local. _ipp._tcp. ipp_server_2
    2013-11-12 08:30:57.457 XperTakeOne[171:60b] findServices:didLoseService: <Service: 0x17673570>
    2013-11-12 08:31:02.678 XperTakeOne[171:60b] netServiceBrowser:didRemoveService: \
        <NSNetService 0x17581730> local. _ipp._tcp. ipp_server_1
    2013-11-12 08:31:02.680 XperTakeOne[171:60b] findServices:didLoseService: <Service: 0x176b25f0>
    
    ...

7.3 A Single Printer

A printer being turned on and then turned off five minutes later.

Note the lines shown in bold for emphasis.

When the printer is turned off the netServiceDidResolveAddress: method is being called for a second time but this time the NSNetService instance has no addresses.

This is the reason for the convoluted code in the FindServices implementation of the netServiceDidResolveAddress:.

Note also that this does not happen when an IPPServer instance is shutdown.

    ...

    2013-11-12 08:32:14.253 XperTakeOne[179:60b] netServiceBrowserWillSearch:
    2013-11-12 08:32:14.976 XperTakeOne[179:60b] netServiceBrowser:didFindService: \
        <NSNetService 0x146b3a50> local. _ipp._tcp. Canon MG6200 series
    2013-11-12 08:32:14.979 XperTakeOne[179:60b] netServiceWillResolve
    2013-11-12 08:32:15.008 XperTakeOne[179:60b] netServiceDidResolveAddress: \
        <NSNetService 0x146b3a50> local. _ipp._tcp. Canon MG6200 series nAddresses == 1
    2013-11-12 08:32:15.011 XperTakeOne[179:60b] findServices:didFindService: <Service: 0x14681460>

    2013-11-12 08:37:10.250 XperTakeOne[179:60b] netServiceDidResolveAddress: \
        <NSNetService 0x146b3a50> local. _ipp._tcp. Canon MG6200 series nAddresses == 0
    2013-11-12 08:37:10.252 XperTakeOne[179:60b] service Canon MG6200 series now has 0 addresses !

    2013-11-12 08:37:11.325 XperTakeOne[179:60b] netServiceBrowser:didRemoveService: \
        <NSNetService 0x146b21d0> local. _ipp._tcp. Canon MG6200 series
    2013-11-12 08:37:11.327 XperTakeOne[179:60b] findServices:didLoseService: <Service: 0x14681460>

    ...

Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

Blog at WordPress.com.

%d bloggers like this: