SSDP client for Swift using the Swift Package Manager. Works on iOS, macOS, tvOS, watchOS and Linux.
SSDPClient is available through Swift Package Manager. To install it, add the following line to your Package.swift
dependencies:
.package(url: "https://github.com/pierrickrouxel/SSDPClient.git", from: "1.0.0")
SSDPClient can be used to discover SSDP devices and services :
import SSDPClient
class ServiceDiscovery {
let client = SSDPDiscovery()
init() {
self.client.delegate = self
self.client.discoverService()
}
}
To handle the discovery implement the SSDPDiscoveryDelegate
protocol :
extension ServiceDiscovery: SSDPDiscoveryDelegate {
func ssdpDiscovery(_: SSDPDiscovery, didDiscoverService: SSDPService) {
// ...
}
}
SSDPDiscovery
provides two instance methods to discover services :
-
discoverService(forDuration duration: TimeInterval = 10, searchTarget: String = "ssdp:all")
- Discover SSDP services for a duration. -
stop()
- Stop the discovery before the end.
The SSDPDiscoveryDelegate
protocol defines delegate methods that you should implement when using SSDPDiscovery
discover tasks :
-
func ssdpDiscovery(_ discovery: SSDPDiscovery, didDiscoverService service: SSDPService)
- Tells the delegate a requested service has been discovered. -
func ssdpDiscovery(_ discovery: SSDPDiscovery, didFinishWithError error: Error)
- Tells the delegate that the discovery ended due to an error. -
func ssdpDiscoveryDidStart(_ discovery: SSDPDiscovery)
- Tells the delegate that the discovery has started. -
func ssdpDiscoveryDidFinish(_ discovery: SSDPDiscovery)
- Tells the delegate that the discovery has finished.
SSDPService
is the discovered service. It contains the following attributes :
host: String
- The host of servicelocation: String?
- The value ofLOCATION
headerserver: String?
- The value ofSERVER
headersearchTarget: String?
- The value ofST
headeruniqueServiceName: String?
- The value ofUSN
headerresponseHeaders: [String: String]?
- Key-Value pairs of all original response headers
Run test:
swift test
If you are targeting iOS 14.0+ you will need to request a special Multicast Entitlement from Apple:
com.apple.developer.networking.multicast
Without the entitlement, you will not be able to test on an actual device; but you can still test in Simulator.
Regarding the local network authorization access, you do not need to explicitly ask for it; the OS will ask the user upon the first time you attempt to access the local network. It's best practice that you provide your own description in the Info.plist with the key NSLocalNetworkUsageDescription
.
You probably run a security issue. You should grant the local network authorization access.
You can handle this error using the following code:
let authorization = LocalNetworkAuthorization()
authorization.requestAuthorization { granted in
if granted {
print("Permission Granted")
let discovery = ServiceDiscovery(delegate: self)
discovery.start()
} else {
print("Permission denied")
}
}