iOS Swift: Sending UDP Packets

This is a beginners guide to sending UDP packets from an iOS device, while using only Swift code. There are plenty of references like this online, but my goal here is to make this as simple and step-by-step as possible. The following are the steps required to make a simple app that sends “Hello World” across your local network in a UDP message.

My Hardware/Setup:

  • OSX Computer (10.11.4)
  • Xcode 7.2.1

Steps:

  1. Go to the SwiftSocket github page and download the repo, and unzip it somewhere on your computer.
  2. Open Xcode and create a new single view project (name it whatever you like).
  3. Drag the folder SwiftSocket\ysocket\ into your Xcode project.
  4. Copy the contents of the attached ViewController.swift file into your own, and change the ip address to that of the computer you are using.
    1. You can check this by opening the Terminal app and using the ‘ifconfig’ command.
  5. Make an interface using Interface Builder that has a single button
  6. Hook the button up to the only IBAction function in the ViewController.swift file using Control-Drag.
  7. Now in the Terminal app run: nc -ul 12345 (This makes your computer listen for UDP messages on that port)
  8. Run on either the simulator or your actual device and press the button to send a UDP packet.
  9. If all was successful you should see “Hello World” pop up on your computer Terminal.

Leave a comment