Skip to content

Latest commit

 

History

History
101 lines (68 loc) · 3.63 KB

README.md

File metadata and controls

101 lines (68 loc) · 3.63 KB

P2PShareKit

Swift Version Platforms

Peer-to-peer sharing using the modern Network.framework, all wrapped up in a handy Swift package.

Securely share data between iOS devices using peer wifi networking (no wifi routers or any established network required)

  • Automatically connect to trusted peers
  • Comms via TLS 1.2
  • Simple Data sharing
  • Automatically re-establish connections to lost peers

Builds upon sample code provided during WWDC2019 - Advances in Networking Part 2

This implementation is currently limited to:

  • iOS 13 or later
  • exclusively uses peer-to-peer wifi

Demo

Refer to the Example project

Sample

Usage

Make sure you have added NSLocalNetworkUsageDescription and NSBonjourServices to your Info.plist

Each device needs to identify itself to others. Build your own identify dictionary based on what makes sense for your app. The PeerInfo record is exchanged before the framework reports a new connection.

let peerInfo = PeerInfo(info: ["name": "Fred"])

Configure a session with your security credentials. Connections are only made with other devices with the same security credentials.

let config = MultipeerSessionConfig(myPeerInfo: peerInfo, 
                                    bonjourService: "_demo._tcp", 
                                    presharedKey: "1234", 
                                    identity: "Demo")

let session = MultipeerSession(config: config)

Finally, set the session callbacks and start the session.

session.peersChangeHandler = { peerInfos in 
     // update any UI that shows connected peers
 }

session.newPeerHandler = { peerInfo in 
    // a good time to sync anything necessary 
}

session.messageReceivedHandler = { peerInfo, data in 
    // Decode data and process
}

session.startSharing()

To send a message, use the peerID from the list of peers returned in peersChangeHandler.

let peerID = peerInfo.peerID
session.send(to: peerID, data: data)

The framework isn't opinionated about how you handle the generic data payload. You can progressively try to decode against expected Codable structs, or use a Codable enum.

Refer to the following blog post for more information and the example PeerShareData that uses a Codable enum: Adopting Network.framework for iOS peer-to-peer connectivity

Integrating

Add the depedency in your Swift package file:

    dependencies: [
        .package(url: "https://github.com/dobster/P2PShareKit", from: "0.2.0")
    ],

Contributing

Feel free to open issues on GitHub or to open pull requests.

License

This project is licensed unter the terms of the MIT license. See LICENSE for more information.