Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom Classes #1

Open
sammysmallman opened this issue Sep 5, 2020 · 2 comments
Open

Custom Classes #1

sammysmallman opened this issue Sep 5, 2020 · 2 comments
Assignees

Comments

@sammysmallman
Copy link

Thanks for the example. Its really nice to see XPC Service in action. I have been attempting to send a custom class across an XPC connection but will little success. I wondered if you have had any success?

@aronskaya
Copy link
Owner

@sammysmallman, I am glad it is useful for you. I didn't want to overcomplicate the sample, but you are right, it is worth adding. For now I can just refer to documentation, see 'Working with Custom Classes' https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingXPCServices.html#//apple_ref/doc/uid/10000172i-SW6-SW7

@aronskaya aronskaya self-assigned this Sep 6, 2020
@sammysmallman
Copy link
Author

sammysmallman commented Sep 6, 2020

Hey @aronskaya,

So i worked it out. The key points are that the class needs to conform to NSSecureCoding and also that you need to have a CodingKeys enum even if your property names are exactly the same.

@objc public class User: NSObject, Codable, NSSecureCoding {  

    public enum CodingKeys: String, CodingKey {
        case name, email
    }

    public static var supportsSecureCoding: Bool = true
    
    public func encode(with coder: NSCoder) {
        coder.encode(name, forKey: "name")
        coder.encode(email, forKey: "email")
    }
    
    public required init?(coder: NSCoder) {
        guard let name = coder.decodeObject(of: NSString.self, forKey: "name") as String?,
                   let email = coder.decodeObject(of: NSString.self, forKey: "email") as String?
        else {
            return nil
        }

        self.name = name
        self.email = email
    }
    
    public let name: String
    public let email: String
    
    public override var description: String { return "name:\(name), email: \(email)"}
    
}

which can be used in the Service Protocol like so:
func login(name: String, email: String, completionHandler: @escaping (User) -> Void)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants