iOS Developer Library

Developer

Foundation Framework Reference NSNetService Class Reference

Options
Deployment Target:

On This Page
Language:

NSNetService

The NSNetService class represents a network service, either one your application publishes or is a client of. This class and the NSNetServiceBrowser class use multicast DNS to convey information about network services to and from your application. The API of NSNetService provides a convenient way to publish the services offered by your application and to resolve the socket address for a service. More...

Inheritance


Conforms To


Import Statement


import Foundation @import Foundation;

Availability


Available in iOS 2.0 and later.
  • Returns the receiver, initialized as a network service of a given type and sets the initial host information.

    Declaration

    Swift

    convenience init!(domain domain: String, type type: String, name name: String)

    Objective-C

    - (instancetype)initWithDomain:(NSString *)domain type:(NSString *)type name:(NSString *)name

    Parameters

    domain

    The domain for the service. To resolve in the default domains, pass in an empty string (@""). To limit resolution to the local domain, use @"local.".

    If you are creating this object to resolve a service whose information your app stored previously, you should set this to the domain in which the service was originally discovered.

    You can also use a NSNetServiceBrowser object to obtain a list of possible domains in which you can discover and resolve services.

    type

    The network service type.

    type must contain both the service type and transport layer information. To ensure that the mDNS responder searches for services, as opposed to hosts, prefix both the service name and transport layer name with an underscore character (“_”). For example, to search for an HTTP service on TCP, you would use the type string "_http._tcp.". Note that the period character at the end of the string, which indicates that the domain name is an absolute name, is required.

    name

    The name of the service to resolve.

    Return Value

    The receiver, initialized as a network service named name of type type in the domain domain.

    Discussion

    This method is the appropriate initializer to use to resolve a service—to publish a service, use initWithDomain:type:name:port:.

    If you know the values for domain, type, and name of the service you wish to connect to, you can create an NSNetService object using this initializer and call resolveWithTimeout: on the result.

    You cannot use this initializer to publish a service. This initializer passes an invalid port number to the designated initializer, which prevents the service from being registered. Calling publish on an NSNetService object initialized with this method generates a call to your delegate’s netService:didNotPublish: method with an NSNetServicesBadArgumentError error.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Initializes the receiver for publishing a network service of type type at the socket location specified by domain, name, and port.

    Declaration

    Swift

    init!(domain domain: String, type type: String, name name: String, port port: Int32)

    Objective-C

    - (instancetype)initWithDomain:(NSString *)domain type:(NSString *)type name:(NSString *)name port:(int)port

    Parameters

    domain

    The domain for the service. To use the default registration domains, pass in an empty string (@""). To limit registration to the local domain, use @"local.".

    You can also use a NSNetServiceBrowser object to obtain a list of possible domains in which you can publish your service.

    type

    The network service type.

    type must contain both the service type and transport layer information. To ensure that the mDNS responder searches for services, as opposed to hosts, prefix both the service name and transport layer name with an underscore character (“_”). For example, to search for an HTTP service on TCP, you would use the type string "_http._tcp.". Note that the period character at the end of the string, which indicates that the domain name is an absolute name, is required.

    name

    The name by which the service is identified to the network. The name must be unique. If you pass the empty string (@""), the system automatically advertises your service using the computer name as the service name.

    port

    The port on which the service is published.

    If you specify the NSNetServiceListenForConnections flag, you may pass zero (0), in which case the service automatically allocates an arbitrary (ephemeral) port for your service. When the delegate’s netServiceDidPublish: is called, you can determine the actual port chosen by calling the service object’s Backward Compatibility Note method or accessing the corresponding property.

    If your app is listening for connections on its own, the value of port must be a port number acquired by your application for the service.

    Discussion

    You use this method to create a service that you wish to publish on the network. Although you can also use this method to create a service you wish to resolve on the network, it is generally more appropriate to use the initWithDomain:type:name: method instead.

    When publishing a service, you must provide valid arguments in order to advertise your service correctly. If the host computer has access to multiple registration domains, you must create separate NSNetService objects for each domain. If you attempt to publish in a domain for which you do not have registration authority, your request may be denied.

    It is acceptable to use an empty string for the domain argument when publishing or browsing a service, but do not rely on this for resolution.

    This method is the designated initializer.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Returns an NSData object representing a TXT record formed from a given dictionary.

    Declaration

    Swift

    class func dataFromTXTRecordDictionary(_ txtDictionary: [NSObject : AnyObject]) -> NSData

    Objective-C

    + (NSData *)dataFromTXTRecordDictionary:(NSDictionary *)txtDictionary

    Parameters

    txtDictionary

    A dictionary containing a TXT record.

    Return Value

    An NSData object representing TXT data formed from txtDictionary. Fails an assertion if txtDictionary cannot be represented as an NSData object.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Returns a dictionary representing a TXT record given as an NSData object.

    Declaration

    Swift

    class func dictionaryFromTXTRecordData(_ txtData: NSData) -> [NSObject : AnyObject]

    Objective-C

    + (NSDictionary *)dictionaryFromTXTRecordData:(NSData *)txtData

    Parameters

    txtData

    A data object encoding a TXT record.

    Return Value

    A dictionary representing txtData. The dictionary’s keys are NSString objects using UTF8 encoding. The values associated with all the dictionary’s keys are NSData objects that encapsulate strings or data.

    Fails an assertion if txtData cannot be represented as an NSDictionary object.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • addresses addresses Property

    A read-only array containing NSData objects, each of which contains a socket address for the service. (read-only)

    Declaration

    Swift

    var addresses: [AnyObject]? { get }

    Objective-C

    @property(readonly, copy) NSArray *addresses

    Discussion

    An array containing NSData objects, each of which contains a socket address for the service. Each NSData object in the returned array contains an appropriate sockaddr structure that you can use to connect to the socket. The exact type of this structure depends on the service to which you are connecting. If no addresses were resolved for the service, the returned array contains zero elements.

    It is possible for a single service to resolve to more than one address or not resolve to any addresses. A service might resolve to multiple addresses if the computer publishing the service is currently multihoming.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

    See Also

    – resolve

  • domain domain Property

    A string containing the domain for this service. (read-only)

    Declaration

    Swift

    var domain: String! { get }

    Objective-C

    @property(readonly, copy) NSString *domain

    Discussion

    This can be an explicit domain name or it can contain the generic local domain name, @"local." (note the trailing period, which indicates an absolute name).

    This property’s value is set when the object is first initialized, whether by your code or by a browser object. See initWithDomain:type:name: for more information.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Creates a pair of input and output streams for the receiver and returns a Boolean value that indicates whether they were retrieved successfully.

    Declaration

    Swift

    func getInputStream(_ inputStream: UnsafeMutablePointer<NSInputStream?>, outputStream outputStream: UnsafeMutablePointer<NSOutputStream?>) -> Bool

    Objective-C

    - (BOOL)getInputStream:(out NSInputStream **)inputStream outputStream:(out NSOutputStream **)outputStream

    Parameters

    inputStream

    Upon return, the input stream for the receiver. Pass NULL if you do not need this stream.

    outputStream

    Upon return, the output stream for the receiver. Pass NULL if you do not need this stream.

    Return Value

    YEStrue if the streams are created successfully, otherwise NOfalse.

    Discussion

    After this method is called, no delegate callbacks are called by the receiver.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • name name Property

    A string containing the name of this service. (read-only)

    Declaration

    Swift

    var name: String { get }

    Objective-C

    @property(readonly, copy) NSString *name

    Discussion

    This value is set when the object is first initialized, whether by your code or by a browser object. See initWithDomain:type:name: for more information.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • type type Property

    The type of the published service. (read-only)

    Declaration

    Swift

    var type: String { get }

    Objective-C

    @property(readonly, copy) NSString *type

    Discussion

    This value is set when the object is first initialized, whether by your code or by a browser object. See initWithDomain:type:name: for more information.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Returns the TXT record for the receiver.

    Declaration

    Swift

    func TXTRecordData() -> NSData!

    Objective-C

    - (NSData *)TXTRecordData

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Sets the TXT record for the receiver, and returns a Boolean value that indicates whether the operation was successful.

    Declaration

    Swift

    func setTXTRecordData(_ recordData: NSData!) -> Bool

    Objective-C

    - (BOOL)setTXTRecordData:(NSData *)recordData

    Parameters

    recordData

    The TXT record for the receiver.

    Return Value

    YEStrue if recordData is successfully set as the TXT record, otherwise NOfalse.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • delegate delegate Property

    The delegate for the receiver.

    Declaration

    Swift

    unowned(unsafe) var delegate: NSNetServiceDelegate?

    Objective-C

    @property(assign) id< NSNetServiceDelegate > delegate

    Discussion

    The delegate must conform to the NSNetServiceDelegate Protocol protocol, and is not retained.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Adds the service to the specified run loop.

    Declaration

    Swift

    func scheduleInRunLoop(_ aRunLoop: NSRunLoop, forMode mode: String)

    Objective-C

    - (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode

    Parameters

    aRunLoop

    The run loop to which to add the receiver.

    mode

    The run loop mode to which to add the receiver. Possible values for mode are discussed in the "Constants" section of NSRunLoop.

    Discussion

    You can use this method in conjunction with removeFromRunLoop:forMode: to transfer a service to a different run loop. You should not attempt to run a service on multiple run loops.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Removes the service from the given run loop for a given mode.

    Declaration

    Swift

    func removeFromRunLoop(_ aRunLoop: NSRunLoop, forMode mode: String)

    Objective-C

    - (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode

    Parameters

    aRunLoop

    The run loop from which to remove the receiver.

    mode

    The run loop mode from which to remove the receiver. Possible values for mode are discussed in the "Constants" section of NSRunLoop.

    Discussion

    You can use this method in conjunction with scheduleInRunLoop:forMode: to transfer the service to a different run loop. Although it is possible to remove an NSNetService object completely from any run loop and then attempt actions on it, it is an error to do so.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Attempts to advertise the receiver’s on the network.

    Declaration

    Swift

    func publish()

    Objective-C

    - (void)publish

    Discussion

    This method returns immediately, with success or failure indicated by the callbacks to the delegate. This is equivalent to calling publishWithOptions: with the default options (0).

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

    See Also

    – stop

  • Attempts to advertise the receiver on the network, with the given options.

    Declaration

    Swift

    func publishWithOptions(_ serviceOptions: NSNetServiceOptions)

    Objective-C

    - (void)publishWithOptions:(NSNetServiceOptions)serviceOptions

    Parameters

    serviceOptions

    Options for the receiver. The supported options are described in NSNetServiceOptions.

    Discussion

    This method returns immediately, with success or failure indicated by the callbacks to the delegate.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • resolve resolve (iOS 2.0)

    Starts a resolve process for the service.

    Deprecation Statement

    Use resolveWithTimeout: instead.

    Declaration

    Objective-C

    - (void)resolve

    Discussion

    Attempts to determine at least one address for the service. This method returns immediately, with success or failure indicated by the callbacks to the delegate.

    In Mac OS X v10.4, this method calls resolveWithTimeout: with a timeout value of 5.

    Import Statement

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • Starts a resolve process of a finite duration for the service.

    Declaration

    Swift

    func resolveWithTimeout(_ timeout: NSTimeInterval)

    Objective-C

    - (void)resolveWithTimeout:(NSTimeInterval)timeout

    Parameters

    timeout

    The maximum number of seconds to attempt a resolve. A value of 0.0 indicates no timeout and a resolve process of indefinite duration.

    Discussion

    During the resolve period, the service sends netServiceDidResolveAddress: to the delegate for each address it discovers that matches the service parameters. Once the timeout is hit, the service sends netServiceDidStop: to the delegate. If no addresses resolve during the timeout period, the service sends netService:didNotResolve: to the delegate.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • port port Property

    The port on which the service is listening for connections. (read-only)

    Declaration

    Swift

    var port: Int { get }

    Objective-C

    @property(readonly) NSInteger port

    Discussion

    If the object was initialized by calling initWithDomain:type:name:port: (whether by your code or by a browser object), then the value was set when the object was first initialized.

    If the object was initialized by calling initWithDomain:type:name:, the value of this property is not valid (-1) until after the service has successfully been resolved (when addresses is non-nil).

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Starts the monitoring of TXT-record updates for the receiver.

    Declaration

    Swift

    func startMonitoring()

    Objective-C

    - (void)startMonitoring

    Discussion

    The delegate must implement netService:didUpdateTXTRecordData:, which is called when the TXT record for the receiver is updated.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Halts a currently running attempt to publish or resolve a service.

    Declaration

    Swift

    func stop()

    Objective-C

    - (void)stop

    Discussion

    The delegate will receive netServiceDidStop: after the service stops.

    It is safe to remove all strong references to the service immediately after calling stop.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Stops the monitoring of TXT-record updates for the receiver.

    Declaration

    Swift

    func stopMonitoring()

    Objective-C

    - (void)stopMonitoring

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • hostName hostName Property

    A string containing the DNS hostname for this service. (read-only)

    Declaration

    Swift

    var hostName: String? { get }

    Objective-C

    @property(readonly, copy) NSString *hostName

    Discussion

    This value is nil until the service has been resolved (when addresses is non-nil).

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

Data Types

  • These constants specify options for a network service.

    Declaration

    Swift

    struct NSNetServiceOptions : RawOptionSetType { init(_ rawValue: UInt) init(rawValue rawValue: UInt) static var NoAutoRename: NSNetServiceOptions { get } static var ListenForConnections: NSNetServiceOptions { get } }

    Objective-C

    enum { NSNetServiceNoAutoRename = 1 << 0 NSNetServiceListenForConnections = 1UL << 1 }; typedef NSUInteger NSNetServiceOptions;

    Constants

    • NoAutoRename

      NSNetServiceNoAutoRename

      Specifies that the network service should not rename itself in the event of a name collision.

      Available in iOS 2.0 and later.

    • ListenForConnections

      NSNetServiceListenForConnections

      Specifies that a TCP listener should be started for both IPv4 and IPv6 on the port specified by this service. If the listening port can't be opened, the service calls its delegate’s netService:didNotPublish: method to report the error.

      The listener supports only TCP connections. If the service’s type does not end with _tcp, publication fails with NSNetServicesBadArgumentError.

      Whenever a client connects to the listening socket, the service calls its delegate’s netService:didAcceptConnectionWithInputStream:outputStream: method with a pair of NSStream objects.

      Available in iOS 7.0 and later.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • If an error occurs, the delegate error-handling methods return a dictionary with the following keys.

    Declaration

    Swift

    let NSNetServicesErrorCode: NSString! let NSNetServicesErrorDomain: NSString!

    Objective-C

    extern NSString *NSNetServicesErrorCode; extern NSString *NSNetServicesErrorDomain;

    Constants

    • NSNetServicesErrorCode

      NSNetServicesErrorCode

      This key identifies the error that occurred during the most recent operation.

      Available in iOS 2.0 and later.

    • NSNetServicesErrorDomain

      NSNetServicesErrorDomain

      This key identifies the originator of the error, which is either the NSNetService object or the mach network layer. For most errors, you should not need the value provided by this key.

      Available in iOS 2.0 and later.

    Import Statement

  • These constants identify errors that can occur when accessing net services.

    Declaration

    Swift

    enum NSNetServicesError : Int { case UnknownError case CollisionError case NotFoundError case ActivityInProgress case BadArgumentError case CancelledError case InvalidError case TimeoutError }

    Objective-C

    typedef enum { NSNetServicesUnknownError = -72000, NSNetServicesCollisionError = -72001, NSNetServicesNotFoundError = -72002, NSNetServicesActivityInProgress = -72003, NSNetServicesBadArgumentError = -72004, NSNetServicesCancelledError = -72005, NSNetServicesInvalidError = -72006, NSNetServicesTimeoutError = -72007, } NSNetServicesError;

    Constants

    • UnknownError

      NSNetServicesUnknownError

      An unknown error occurred.

      Available in iOS 2.0 and later.

    • CollisionError

      NSNetServicesCollisionError

      The service could not be published because the name is already in use. The name could be in use locally or on another system.

      Available in iOS 2.0 and later.

    • NotFoundError

      NSNetServicesNotFoundError

      The service could not be found on the network.

      Available in iOS 2.0 and later.

    • ActivityInProgress

      NSNetServicesActivityInProgress

      The net service cannot process the request at this time. No additional information about the network state is known.

      Available in iOS 2.0 and later.

    • BadArgumentError

      NSNetServicesBadArgumentError

      An invalid argument was used when creating the NSNetService object.

      Available in iOS 2.0 and later.

    • CancelledError

      NSNetServicesCancelledError

      The client canceled the action.

      Available in iOS 2.0 and later.

    • InvalidError

      NSNetServicesInvalidError

      The net service was improperly configured.

      Available in iOS 2.0 and later.

    • TimeoutError

      NSNetServicesTimeoutError

      The net service has timed out.

      Available in iOS 2.0 and later.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.