Swift Siesta and NSURLSession - siesta-swift

Looking for a way to still use an NSURLSession but override the siestaNetworkingProvider implementation to return my own NetworkingProvider. This seems impossible however since you can not override protocol extensions.

You can’t override what happens when you pass an NSURLSession for the networking: param when creating a service — but that is only a convenience anyway.
You can pass your custom networking provider directly:
struct MyFancyProvider: NetworkingProvider {
let session: NSURLSession
// ...
}
Service(baseURL: "http://whatever", networking: MyFancyProvider(...))
(This works because NetworkingProvider itself implements NetworkingProviderConvertible.)

Related

Swift Concurrency: Conforming a 3rd party library to actor isolation

I am in the process of converting some code bases over to using Swift concurrency and am running into a few snags along the way.
The current project I'm working through has a few 3rd party libraries that it relies on, and in one of those libraries, there is a delegate protocol that requires some data values to be returned from its methods.
Here is an example of the type of delegate methods in the library:
public protocol FooDelegate: AnyObject {
func foo() -> CGFloat
}
I'm attempting to return some values from the implementation of the protocol like this:
extension ViewController: FooDelegate {
func foo() -> CGFloat { // <- Cannot satisfy requirement from protocol
view.bounds.height
}
}
Without any modification, the above is implicitly isolated to the MainActor and can not satisfy the requirement from the FooDelegate protocol.
One solution I've tried was to mark the function implementation with nonisolated:
extension ViewController: FooDelegate {
nonisolated func foo() -> CGFloat {
view.bounds.height // <- Cannot be referenced from a non-isolated context
}
}
This did not work though because it references the view controller's view. That results in the view being referenced from a non-isolated synchronous context. (There are also a few other issues with this since any values that are passed through into any of the delegate functions need to conform to Sendable to be able to be passed across actors).
My question is, is there a way to take a 3rd party library and extend it somehow so that it conforms to proper actor isolation without having to modify its source code?

gomobile: binding callbacks for ObjC

I have a Go interface
type GetResponse interface { OnResult(json string) }
I have to subscribe on that event OnResult from ObjC using this interface.
func Subscribe( response GetResponse){ response.OnResult("some json") }
ObjC bind gives me a corresponding protocol and a basic class
#interface GetResponse : NSObject <goSeqRefInterface, GetResponse> {
}
#property(strong, readonly) id _ref;
- (instancetype)initWithRef:(id)ref;
- (void)onResult:(NSString*)json;
#end
So, I need to get this json in my ObjC env. How can I do that?
Subclassing If I subclass this GetResponse or just use it as is and pass to Subscribe routine, it crashes
'go_seq_go_to_refnum on objective-c objects is not permitted'
Category if I create struct on Go side with the protocol support, I can't subclass it but at least it's not crashes:
type GetResponseStruct struct{}
func (GetResponseStruct) OnResult(json string){log.Info("GO RESULT")}
func CreateGetResponse() *GetResponseStruct{ return &GetResponseStruct{}}
I have a solid object without obvious way to hook up my callback. If I make a category and override the onResult routine, it's not called. Just because overriding existing methods of class is not determined behavior according to AppleDoc. Anytime OnResult called from Go, the default implementation invokes and "GO RESULT" appears.
Swizzling I tried to use category and swizzle (replace method's implementation with mine renamed method) but it only works if I call onResult from ObjC env.
Any way to solve my issue? Or I just red the doc not very accurately? Please help me
I ran into a similar issue today. I thought it was a bug in gomobile but it was my misunderstanding of swift/objc after all. https://github.com/golang/go/issues/35003
The TLDR of that bug is that you must subclass the protocol, and not the interface. If you are using swift then you can subclass the GetResponseProtocol:
class MyResponse: GetResponseProtocol
If in objc, then you probably want to directly implement the GetResponse protocol, rather than subclassing the interface.

Swift access control on protocol conformance

I have a private protocol defined in a file as below
private protocol testProtocol {
func testFunc1()
func testFunc2()
}
A public class conforms to the above protocol as follows
public class testClass : testProtocol {
func testFunc1() {}
func testFunc2() {}
}
As per apples documentation , the members of a public class get internal access control by default unless it is explicitly set to a different access control modifier.
The documentation also says that a type's conformance to a protocol with a lower access control will make the type's implementation of the protocol access control the same as that of the protocol. In this scenario since the type's access control is public and the protocols access control is private , the methods testfunc1 and testfunc2 should get an access control of private.
When the class is instantiated in a different source file and the methods are accessed as below , the compiler does not show an error which is not expected as the methods should be private as per the guidelines
var test: testClass = testClass()
test.testFunc1()
Is this expected behavior ? Am i missing something?
Apple Documentation says:
When you write or extend a type to conform to a protocol, you must ensure that the type’s implementation of each protocol requirement has at least the same access level as the type’s conformance to that protocol.
According to this I assume that implementing methods testFunc1 and testFunc2 with another access control modifier inside testClass just overrides that from protocol. If you use default protocol implementation of this methods like the following compiler will return error:
extension testProtocol {
func testFunc1() {}
func testFunc2() {}
}
As far as Swift is Protocol Oriented Language with replacing inheritance with protocols it's probably reasonable if you want to change protocol defined access level of function inside your custom class.
According to Apple's documentation:
When you write or extend a type to conform to a protocol, you must ensure that > the type’s implementation of each protocol requirement has at least the same > access level as the type’s conformance to that protocol.
Please be aware of the "at least" in the doc, it means that the as long as the access level of the type's implementation of the protocol requirements is higher or equal to the access level of the protocol, it will be ok. In your case, testFunc1 and testFunc2 from testClass have the default access level of internal, it is higher than access level of private. So actually the two methods in testClass get the access level of internal, and compiler won't treat it as en error.
We can change your code a little bit as follows:
fileprivate protocol TestProtocol {
func testFunc1()
func testFunc2()
}
public class TestClass : TestProtocol {
public func testFunc1() {}
public func testFunc2() {}
}
This piece of code will also compile without an error.

Cannot declare a public protocol extension with internal requirements

I am programming a media player app and created my own framework for managing all the player functionality. In this framework I have a public protocol called PlayerControllerType and an internal protocol _PlayerControllerType. In PlayerControllerType I have declared all the methods and properties, which should be accessible from outside the framework. In _PlayerControllerType I have defined a couple of properties, which are used by the concrete types implementing PlayerControllerType inside the framework. One of these types is PlayerController. Its declaration is as follows:
public class PlayerController<Item: Equatable>: NSObject, PlayerControllerType,
_PlayerControllerType, QueueDelegate
Now I want to provide a couple of default implementations for the classes in my framework, which conform to PlayerControllerType and the internal _PlayerControllerType, for example:
import Foundation
import MediaPlayer
public extension PlayerControllerType where Self: _PlayerControllerType, Item == MPMediaItem, Self.QueueT == Queue<Item>, Self: QueueDelegate {
public func setQueue(query query: MPMediaQuery) {
queue.items = query.items ?? []
}
}
This works as expected in Xcode 7 Beta 4. Yesterday I updated to Beta 6 and got this error:
"Extensions cannot be declared public because its generic requirement uses an internal type" (also see screenshot).
I find this error irritating. Of course no type outside of my framework benefits of this extension because it cannot access the internal protocol _PlayerControllerType, but it is very useful for the types inside my framework which implement both PlayerControllerType and _PlayerControllerType.
Is this just a bug in the Swift compiler or is this the intended behavior?
It's is pretty unfortunate that this doesn't work anymore because now I have to put these methods into a newly created base class for all my PlayerControllers.
Any help or feedback would greatly appreciated.
Kai
EDIT:
Here is a shortened example of the protocols and their extensions:
public protocol PlayerControllerType {
typealias Item
var nowPlayingItem: Item {get}
func play()
}
protocol _PlayerControllerType {
var nowPlayingItem: Item {get set}
}
public extension PlayerControllerType where Self: _PlayerControllerType {
/*
I want to provide a default implementation of play() for
all my PlayerControllers in my framework (there is more than one).
This method needs to be declared public, because it implements a
requirement of the public protocol PlayerControllerType.
But it cannot be implemented here, because this extension
has the requirement _PlayerControllerType. It needs this requirement,
because otherwise it cannot set the nowPlayingItem. I don't want to
expose the setter of nowPlayingItem.
I could make a base class for all PlayerControllers, but then I'm
restricted to this base class because Swift does not support
multiple inheritance.
*/
public func play() {
if nowPlayingItem == nil {
nowPlayingItem = queue.first
}
// Other stuff
}
}
You need to declare an access level of the _PlayerControllerType protocol as 'public'.
public protocol _PlayerControllerType {
// some code
}
According to (The Swift Programming Language - Access Control),
A public members cannot be defined as having an internal or private type, because the type might not be available everywhere that the
public variable is used. Classes are declared as internal by default,
so you have to add the public keyword to make them public.
A member (class/protocol/function/variable) cannot have a higher
access level than its parameter types and return type, because the
function could be used in situations where its constituent types are
not available to the surrounding code.

Typhoon - How to inject parameter which conforms to PROTOCOL instead of CLASS

I have class which represents logged user
public class User: NSObject {
init(authenticator: Authenticator) {
self.authenticator = authenticator
}
...
}
Its only initial arguments is object which conforms to Authenticator protocol
protocol Authenticator
{
func authenticate(login:String , password:String , handler: (result:AuthenticationResult)->() )
}
In my case the Auth object is instance of class BackendService
My typhoon assembly definition is:
public dynamic func user() -> AnyObject {
return TyphoonDefinition.withClass(User.self) {
(definition) in
definition.useInitializer("initWithAuthenticator") {
(initializer) in
initializer.injectParameterWith( self.backendService() )
}
}
}
Application cause runtime-error
'Method 'initWithAuthenticator' has 0 parameters, but 1 was injected. Do you mean 'initWithAuthenticator:'?'
If i change init method to 'initWithAuthenticator:' it crashes with
'Method 'initWithAuthenticator:' not found on 'PersonalMessages.User'. Did you include the required ':' characters to signify arguments?'
At the present time, it is necessary to add the '#objc' directive to Swift protocols to have them be available for dependency injection with Typhoon. Without it the objective-c runtime's introspection and dynamic dispatch features arent available and these are required.
Similarly, in the case of a class it must extend from NSObject or have the '#objc' directive, otherwise it will also use C++ style vtable dispatch and have (essentially) no reflection. In the case of private vars or methods, they must also have the 'dynamic' modifier.
While vtable dispatch is faster, it prevents runtime method interception which many of Cocoa's most powerful features, such as KVO rely on. So both paradigms are important and its impressive that Swift can switch between them. In the case of protocols though, using the '#objc' directive is a little unfortunate as it implies a 'legacy' behavior. Perhaps 'dynamic' would've been better?
dynamic protocol Authenticator //Not supported but would've been a nicer than '#objc'?
Or perhaps another way to imply that dynamic behavior is required would be to have the protocol extend the NSObject protocol, however this does not work. So using '#objc' is the only choice.
Meanwhile, for classes the requirement to extend NSObject isn't really noticible as far as working with Cocoa/Touch apps goes.

Resources