Home > Software engineering >  conforming to a protocol require delegate variable be available in ios13
conforming to a protocol require delegate variable be available in ios13

Time:03-12

having this protocol

 public protocol URLSessionWebSocketTaskProtocol {

    func send(_ message: URLSessionWebSocketTask.Message, completionHandler: @escaping (Error?) -> Void)
    func receive(completionHandler: @escaping (Result<URLSessionWebSocketTask.Message, Error>) -> Void)
    func sendPing(pongReceiveHandler: @escaping (Error?) -> Void)
    func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?)
    func resume()
}

and conforming to it in this part

extension URLSessionWebSocketTask: URLSessionWebSocketTaskProtocol {}

works fine, but I need to have delegate property in the protocol so modified the protocol to this

public protocol URLSessionWebSocketTaskProtocol {

func send(_ message: URLSessionWebSocketTask.Message, completionHandler: @escaping (Error?) -> Void)
func receive(completionHandler: @escaping (Result<URLSessionWebSocketTask.Message, Error>) -> Void)
func sendPing(pongReceiveHandler: @escaping (Error?) -> Void)
func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?)
func resume()
var delegate: URLSessionTaskDelegate? { get set}

}

now the compiler tells that

Protocol 'URLSessionWebSocketTaskProtocol' requires 'delegate' to be available in iOS 13.0.0 and newer

the target minimun version is set to iOS 13, so it should be necessary to add the @available(iOS 13.0, *), but added any way and there is not change the compilers keeps telling that protocol requires delegate to be available in iOS 13. URLWebSocketTask does not have a delegate property per se it inherits from URLSessionTask that have a delegate Property of type URLSessionTaskDelegate and URLWebSocketTaskDelegate comforms to URlSessionTaskDelegate.

so how I could add a delegate to the protocol and the conformance does not show that error.

CodePudding user response:

The URLSessionWebSocketTask is-a NSURLSessionTask, which has delegate only (!!) since iOS 15:

@interface NSURLSessionTask : NSObject <NSCopying, NSProgressReporting>

@property (nullable, retain) id <NSURLSessionTaskDelegate> delegate 
API_AVAILABLE(macos(12.0), ios(15.0), watchos(8.0), tvos(15.0));

so if you want to fit that API contract, you need to do same in your protocol, like:

public protocol URLSessionWebSocketTaskProtocol {

    // ... other methods here

    @available(iOS 15, *)                               // << here !!
    var delegate: URLSessionTaskDelegate? { get set }

}

of course alternate is to make extension limited to iOS15 , like

@available(iOS 15, *)
extension URLSessionWebSocketTask: URLSessionWebSocketTaskProtocol {
}

Verified with Xcode 13.2.1

CodePudding user response:

You have to add the var in class extension. This may not related but who knows ?

  • Related