Embedding a Live Stream Video in an iOS App Using SwiftUI

One of my apps, SatNow, is a simple app for tracking the current location of the International Space Station. In addition to being able to see when it will next pass over you and the weather forecast for that passing, you can also view a live stream from the ISS. This feature was surprisingly simple to implement, thanks to SwiftUI.

Getting a live stream URL#

Funnily enough, this is the most difficult part of this tutorial. If you want to embed a live stream that isn’t owned by yourself, you’ll need to find the URL yourself. In my case the stream is hosted on UStream, and I was able to inspect the webpage to extract the URL.

Enabling Insecure Network Connections#

Depending on the source of your live stream, you may need to disable App Transport Security, which improves privacy and data integrity for apps. To do this, open Info.plist, and add a new row. As the key, enter NSAppTransportSecurity, which will create a dictionary inside your plist. Click on the arrow to the left of this key to ensure it is facing down, and then click the add button again. For this key, enter NSAllowsArbitraryLoads, and change the value to YES.

Embedding the live stream into your app#

Once you have your URL, the code is relatively straightforward! First, import AVKit at the top of ContentView.swift. Then, create an instance AVPlayer of, passing in the live stream’s URL. Common methods such as play() and pause() can be used on this instance, but that won’t do much until we add the player to our body.

Inside the body, replace the contents with a VideoPlayer view, which takes the AVPlayer instance as an argument. At this point, all the code needed to embed a live stream into an app is written!

To improve the user experience, it may be desirable to have the live stream automatically start when it is open. To do that, add the .onAppear() view modifier to the VideoPlayer, and then add player.play() inside the function body to have the player automatically start.

import SwiftUI
import AVKit

struct ContentView: View {
    
    private let player = AVPlayer(url: URL(string: "http://iphone-streaming.ustream.tv/uhls/17074538/streams/live/iphone/playlist.m3u8")!)
    
    var body: some View {
        VideoPlayer(player: player)
            .onAppear() {
                player.play()
            }
    }
}

Conclusion#

Previously, the code needed to embed any kind of video into an iOS app required many lines of code. But no more! SwiftUI continues to blow my mind with how simple it is to use.

If this tutorial helped you in any way, I’d really appreciate a share on Twitter. You can reach out to me via Twitter if you have any questions, or to show me what you’ve been up to!