📹 Framework to Play a Video in the Background of any UIView

Overview

Build Status codecov doccov Platform Swift MIT License CocoaPods Version Status Carthage compatible

SwiftVideoBackground is an easy to use Swift framework that provides the ability to play a video on any UIView. This provides a beautiful UI for login screens, or splash pages, as implemented by Spotify and many others.

Features

  • Play a video with one line of code
  • Supports local videos && videos from a web URL
  • Automatically adjusts when device orientation changes
  • Automatically resumes video when app re-enters foreground
  • Pause, resume, restart, and other controls
  • Loop videos (optional)
  • Mute sound (optional)
  • Darken videos so overlying UI stands out more (optional)
  • Documentation

Contents

  1. Integration
  2. Migration Guide
  3. Usage
  4. License
  5. Authors

Integration

CocoaPods

You can use CocoaPods to install SwiftVideoBackground by adding it to your Podfile:

For Swift 5:

pod 'SwiftVideoBackground'

For Swift 4:

pod 'SwiftVideoBackground', '~> 3.0'

For Swift 3:

pod 'SwiftVideoBackground', '0.06'

Carthage

You can use Carthage to install SwiftVideoBackground by adding it to your Cartfile:

github "dingwilson/SwiftVideoBackground"

Manually

To use this library in your project manually you may:

  1. for Projects, just drag VideoBackground.swift to the project tree
  2. for Workspaces, include the whole SwiftVideoBackground.xcodeproj

Migration Guide

Version 3.0.0

Version 2.0.0

See the quick migration guide.

Usage

Example

import UIKit
import SwiftVideoBackground

class MyViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()

    try? VideoBackground.shared.play(view: view, videoName: "myVideo", videoType: "mp4")

    /* or from URL */

    let url = URL(string: "https://coolVids.com/coolVid.mp4")!
    VideoBackground.shared.play(view: view, url: url)
  }
}

Documentation for Version 0.06 (Swift 3) can be found here.

Customization

play() has four additional optional parameters for customization:

  • darkness: CGFloat - Value between 0 and 1. The higher the value, the darker the video. Defaults to 0.
  • isMuted: Bool - Indicates whether video is muted. Defaults to true.
  • willLoopVideo: Bool - Indicates whether video should restart when finished. Defaults to true.
  • setAudioSessionAmbient: Bool - Indicates whether to set the shared AVAudioSession to ambient. If this is not done, audio played from your app will pause other audio playing on the device. Defaults to true.

So for example:

VideoBackground.shared.play(
    view: view,
    videoName: "myVideo",
    videoType: "mp4",
    darkness: 0.25,
    isMuted: false,
    willLoopVideo: true,
    setAudioSessionAmbient: true
)

-> will play the video with the sound on, slightly darkened, continuously looping, and without affecting other sources of audio on the device.

Any combination of the parameters can be included or left out.

setAudioSessionAmbient only has an effect in iOS 10.0+. For more information, see the docs.

Controls

  • pause() - Pauses the video.
  • resume() - Resumes the video.
  • restart() - Restarts the video.
  • getThumbnailImage(from: URL, at: CMTime) - Generate an image from the video to show as thumbnail.
  • darkness - Change this CGFloat to adjust the darkness of the video. Value 0 to 1. Higher numbers are darker. Setting to an invalid value does nothing.
  • isMuted - Change this Bool to mute/unmute the video.
  • willLoopVideo - Change this Bool to set whether the video restarts when it ends.
  • videoGravity - Default is .resizeAspectFill. Change to .resizeAspect (doesn't fill view) or .resize (doesn't conserve aspect ratio).
  • playerLayer - The AVPlayerLayer that can be accessed for advanced control and customization of the video.

Singleton

SwiftVideoBackground includes a singleton instance that can be conveniently accessed with VideoBackground.shared. An instance of VideoBackground can only play one video on one UIView at a time. So if you need to play on multiple UIViews, you need to retain an instance of VideoBackground for each UIView:

let videoBackground1 = VideoBackground()

Adding Videos To Your Project

In order to play local videos, you must add them to your project:

  1. Open project navigator
  2. Select your target
  3. Select Build Phases
  4. Select Copy Bundle Resources
  5. Click + to add a video

add video to project

License

SwiftVideoBackground is released under an MIT License. See LICENSE for details.

Authors

Wilson Ding, Quan Vo

Copyright © 2016-present Wilson Ding.

Please provide attribution, it is greatly appreciated.

Comments
  • BREAKING CHANGE: Add several controls. Remove multi vid support.

    BREAKING CHANGE: Add several controls. Remove multi vid support.

    What does this PR do?

    - added new APIs under `UIView` extension. Videos can now be played with: - `myView.playVideo(videoName:videoType)` - `alpha`, `isMuted`, & `willLoopVideo` can be changed at runtime with: - `myView.setVideoAlpha(_:)` etc - added `pauseVideo()` & `resumeVideo()` - the `VideoBackground` class is no longer needed: - the settings, state observers, etc for a view are automatically managed under the covers through other means - old APIs are still usable, but deprecation warnings added - removed multi vid support for now (migrating this feature to the new structure would have been a lot of work)* - added docs - profiled

    *I could make this a non breaking PR by implementing this. Doable.

    TODO:

    • more testing with changing alpha, isMuted, etc.
    • clean up example view controller and storyboard (currently using them to test stuff, ignore ftm)
    • update README

    Large PR so review incrementally at your leisure. Also let me know if I've gotten any of the devops syntax/etc wrong.

    • add support for playing video from web URL
    • add APIs for pause, restart, resume, alpha, isMuted, & willLoopVideo
    • ~~will try to implement merging~~ remove multi vid support
    • beefed up example
    • add #32
    • add docs
    • update README

    TODO:

    • [x] add stuff to README regarding false positive memory leak on simulator with vids with sound
    • [x] add recommendation to use FFMPEG to merge vids
    • [x] flesh out tests #50
    • [x] deprecate alpha APIs
    • [x] change alpha to darkness

    What issues (if any) are related to this PR? Or why was this change introduced?

    Closes #23 Closes #31 Closes #32 Closes #50 Closes #52 Closes #54

    Checklist

    • [x] Does this contain code changes?
    • [x] Does this have tests?
    • [x] Does this have documentation?
    • [x] Does this break the public API (Requires major version bump)?
    • [x] Is this a new feature (Requires minor version bump)?
    opened by quanvo87 25
  • 2.0

    2.0

    Opening PR now to begin code review. Will update README and jazzy when rdy.

    Tested on my other app.

    Example usage of new API would be:

    import UIKit
    import BackgroundVideo
    
    class MyViewController: UIViewController {
      private let backgroundVideo = BackgroundVideo()
    
      override func viewDidLoad() {
        super.viewDidLoad()
    
        backgroundVideo.play(view: view, videoName: "worldstar", videoType: "mp4")
      }
    }
    

    play() has three additional optional parameters:

    • isMuted: defaults to true
    • opacity: defaults to 1.0
    • loopVideo: defaults to true

    One caveat of this approach is that if the user wants the video to loop, they need to declare an instance of BackgroundVideo in such a way that it's retained for the life of the UIView they want it to play on (like in the example above). If it's just declared in a function, the instance gets deallocated as soon as the function ends and the notification center cannot alert it to repeat the video.


    I also think some work needs to be done regarding the audio. Right now, even when muted, if the user is listening to music on the their phone, then opens the app using this API, their audio will be "dampened".

    opened by quanvo87 12
  • Issue with rotation

    Issue with rotation

    If I rotate my iPad the video doesn't adapt to the screen size (please check GIF: https://giphy.com/gifs/l4pSVnVwldE37HkuQ). Is there any way I can fix this?

    bug 
    opened by csr 11
  • Updated README with FFmpeg blog post and fixed typos

    Updated README with FFmpeg blog post and fixed typos

    What does this PR do?

    Updates README with link to FFmpeg blog post

    What issues (if any) are related to this PR? Or why was this change introduced?

    Closes #56

    Checklist

    • [ ] Does this contain code changes?
    • [ ] Does this have tests?
    • [ ] Does this have documentation?
    • [ ] Does this break the public API (Requires major version bump)?
    • [ ] Is this a new feature (Requires minor version bump)?
    opened by dingwilson 10
  • Crash on cleanUp

    Crash on cleanUp

    https://github.com/dingwilson/SwiftVideoBackground/blob/78cbe752332dfa3766a899ff794fbd567e355b5c/SwiftVideoBackground/Sources/VideoBackground.swift#L181

    Crashes on above line due to the superview of that view being nil sometimes

    opened by ndemie 8
  • add pause and resume

    add pause and resume

    Scenario:

    • a video is being played on a UIView
    • that UIView becomes hidden (ie another view controller is pushed onto the stack)
    • that UIView becomes un-hidden again (ie previously mentioned view controller is closed)

    What happens: It seems that while UIView was hidden, the video wasn't playing, and when it gets un-hidden, it plays the video super fast, up to the point that it would be if it wasn't paused.

    Not sure if that makes sense or if that's actually what's happening, but I know there is some super fast video playing after a hidden/un-hidden scenario.

    I think a fix would be to implement pause() and resume(). I'm hoping correctly using these methods when you expect your view to be hidden/un-hidden fixes this.

    This might also be able to be automated if desired (not sure if possible, not sure of side effects).

    opened by quanvo87 8
  • Changing video.

    Changing video.

    Hello, I'm trying to use this for onboarding videos. As the user hits next I would like to change the video using the same view. Anyway to do this with this plugin? It currently just stays the same video even though I'm trying to update it when the user hits next.

    Thanks!

    opened by gilosborne 7
  • Added example project, basic tests, and CodeCov

    Added example project, basic tests, and CodeCov

    Closes #28 Closes #49

    Make sure to squash and merge the commits

    Tasks:

    • [x] Add example project
    • [x] Move source files to Sources/ folder
    • [x] Ensure jazzy docs don't pick up files from example project
    • [ ] Ensure this doesn't break Cocoapods
    • [ ] Ensure this doesn't break Carthage
    • [x] Add tests
    • [x] Add Codecov Integration (#49)
    opened by dingwilson 6
  • Playing different videos on each UITableViewCell

    Playing different videos on each UITableViewCell

    Hi @dingwilson , I'm trying to create a tableView with each cell has a separate video. Assuming that the tableView cells are only 2 for the below code Video string is placed in a static array and instances of VideoBackground

    var videoArray = ["video1", "video2", "video3", "video4", "video5"] let videoBackground1 = VideoBackground() let videoBackground2 = VideoBackground()

    and inside the cellforRow indexPath method (which is weird for me, but don't know where to place, where a UIView is placed inside the cell.

    if indexPath.row == 0{ try? videoBackground1.play(view: cell.videoView, videoName: videoArray[0], videoType: "mp4", isMuted: false) }else if indexPath.row == 1 { try? videoBackground2.play(view: cell.videoView, videoName: videoArray[1], videoType: "mp4", isMuted: false) }

    In above case, the vice is not playing or showing, so when replacing the instance with the singleton, it's showing the last cell only due to the single AVPlayer instance.

    opened by MohdElBasyouni 5
  • configurable videoGravity, caching, and thumbnail image

    configurable videoGravity, caching, and thumbnail image

    What does this PR do?

    These are several features we need in a project:

    • changing the default videoGravity
    • caching videos from remote URLs
    • creating thumbnail image from a video

    What issues (if any) are related to this PR? Or why was this change introduced?

    No issues, just enhancements.

    Checklist

    • [x] Does this contain code changes?
    • [ ] Does this have tests?
    • [x] Does this have documentation?
    • [x] Does this break the public API (Requires major version bump)?
    • [x] Is this a new feature (Requires minor version bump)?
    opened by yonat 4
  • Dependency

    Dependency "SwiftVideoBackground" has no shared framework schemes for any of the platforms: iOS

    When installing with carthage using github "dingwilson/SwiftVideoBackground" and then running:

    carthage update --platform iOS
    

    The process fails with:

    Dependency "SwiftVideoBackground" has no shared framework schemes for any of the platforms: iOS

    I tried with both carthage 0.28.0 and 0.29.0 with the same problem. Not sure what the issue is, but a solution on stack overflow talks about needing the proper targets in xcshareddata/xcschemes/.xcscheme.

    If you compare your single scheme to say Alamofire's https://github.com/Alamofire/Alamofire/tree/master/Alamofire.xcodeproj/xcshareddata/xcschemes maybe this provides a clue?

    bug 
    opened by sjmueller 4
  • How to define that video from Web is loading and how can i display it to user?

    How to define that video from Web is loading and how can i display it to user?

    Hi, your library is cool. However, i would like to know how to track that video from Web is loading? I want to show to user something like loading spinner during the video loading.

    opened by IKorabel 1
  • Url to pull video stream in the background?

    Url to pull video stream in the background?

    let url = URL(string: "https://viewer.millicast.com/v2?streamId=w9dvKs/kkmy5gxc")! VideoBackground.shared.play(view: view, url: url)

    So i have the above code in my viewDidLoad(), and for the videos it works great. However, I want to pull from a live stream and display it, but it always is a blank screen even though the stream is working. Would you have any ideas on how to resolve that issue or is it maybe on the streams end?

    Kind regards, Andrew Bolt

    opened by BoltAlot2 1
  • How do you access the video layer?

    How do you access the video layer?

    I'm trying to figure out how to access the video layer so I can do some animation on it.

    The doc says playerLayer is the layer. but how do I use this in my code?

    I've tried this and it does work:

    let playerLayer = VideoBackground()

    and

    let playerLayer = AVPlayerLayer()

    any help would be appreciated.

    opened by phiasco12 0
  • cannot play video saved into phone storage

    cannot play video saved into phone storage

    Dear sir, Thanks so much for the Ince library. Currently I am trying too play mp4 files that is saved into phone storage. I cannot run it. My code is :

    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths[0] print(documentsDirectory)

        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
           let url = NSURL(fileURLWithPath: path)
           if let pathComponent = url.appendingPathComponent("water.mp4") {
               let filePath = pathComponent.path
               let fileManager = FileManager.default
               if fileManager.fileExists(atPath: filePath) {
                   print("FILE AVAILABLE")
                let url = URL(string: filePath)!
                videoBackground1.play(view: view1, url: url, darkness: 0.1)
                
               } else {
                   print("FILE NOT AVAILABLE")
               }
           } else {
               print("FILE PATH NOT AVAILABLE")
           }
    

    below is debug code:FILE AVAILABLE 2021-01-07 22:48:54.253683+0200 yarab[18271:807739] [plugin] AddInstanceForFactory: No factory registered for id <CFUUID 0x600003c5d3e0> F8BB1C28-BAE8-11D6-9C31-00039315CD46 2021-01-07 22:48:54.299434+0200 yarab[18271:807835] NSURLConnection finished with error - code -1002

    opened by waleedmakarem 1
Releases(3.3.0)
Owner
Wilson Ding
I build cool stuff people use @limebike | formerly @amzn @IBM-Swift
Wilson Ding
Twinkle is a Swift and easy way to make any UIView in your iOS or tvOS app twinkle.

Twinkle ✨ Twinkle is a Swift and easy way to make any UIView in your iOS or tvOS app twinkle. This library creates several CAEmitterLayers and animate

patrick piemonte 600 Nov 24, 2022
A way to quickly add a notification badge icon to any view. Make any view of a full-fledged animated notification center.

BadgeHub A way to quickly add a notification badge icon to any view. Demo/Example For demo: $ pod try BadgeHub To run the example project, clone the r

Jogendra 772 Dec 28, 2022
A framework which helps you attach observers to `UIView`s to get updates on its frame changes

FrameObserver is a framework that lets you attach observers to any UIView subclass and get notified when its size changes. It doesn't use any Method S

null 11 Jul 25, 2022
A flexible container view featuring a solid background with rounded corners.

A flexible container view featuring a solid background with rounded corners.

Tim Oliver 13 Jan 22, 2022
Creating a blurred window background in Mac Catalyst

TransparentChrome In response to a developer question, I looked for the easiest way to provide a translucent full-window chrome with a blurred backgro

Steven Troughton-Smith 37 Dec 2, 2022
Play BreakOut while loading - A playable pull to refresh view using SpriteKit

BreakOutToRefresh Play BreakOut while loading - A playable pull to refresh view using SpriteKit BreakOutToRefresh uses SpriteKit to add a playable min

Dominik Hauser 2.5k Jan 5, 2023
Simple battery shaped UIView

BatteryView Simple battery shaped UIView. Usage let batteryView = BatteryView(frame: smallRect) batteryView.level = 42 // anywhere in 0...100 batteryV

Yonat Sharon 50 Sep 19, 2022
UIView and CGRect extension that adds properties to manipulate them efficiently

Geometry Geometry is a UIView and CGRect extension that lets you work with view and rect geometry easier. It adds the following properties to UIView:

Tuomas Artman 92 Sep 7, 2022
An iOS Library that makes shadows management easy on UIView.

ShadowView is an iOS Shadow library that makes view's shadow implementation easy and sweet ?? ?? . Add simple shadows to add a gaussian blurred projec

Pierre 404 Dec 8, 2022
High performance and lightweight UIView, UIImage, UIImageView, UIlabel, UIButton, Promise and more.

SwiftyUI High performance and lightweight UIView, UIImage, UIImageView, UIlabel, UIButton and more. Features SwiftyView GPU rendering Image and Color

Haoking 336 Nov 26, 2022
Custom Beautiful UIView For Handling IDs in iOS

IDView Custom Beautiful UIView For Handling IDs in iOS Setup Set the placeholder images for the front and back faces. override func viewDidLoad()

Omar Labib 6 Aug 21, 2021
Easily use UIKit views in your SwiftUI applications. Create Xcode Previews for UIView elements

SwiftUIKitView Easily use UIKit views in SwiftUI. Convert UIView to SwiftUI View Create Xcode Previews from UIView elements SwiftUI functional updatin

Antoine van der Lee 682 Dec 29, 2022
A swift PropertyWrapper to provide automatic NSView/UIView invalidation when the properties value changes.

A swift PropertyWrapper to provide automatic NSView/UIView invalidation when the properties value changes. It duplicates the @Invalidating propertyWrapper for build targets prior to macOS 12 and iOS 15.

Darren Ford 8 Oct 15, 2021
Easily add drop shadows, borders, and round corners to a UIView.

Easily add drop shadows, borders, rounded corners to a UIView. Installation CocoaPods Add the follwing to your Podfile: pod 'Shades' Usage Storyboard

Aaron Sutton 14 Jun 20, 2020
Anchorage - Single file UIView drag and drop system

anchorage Single file UIView drag and drop system anchors.mp4 License Copyright

● ●●   ● 3 Jan 28, 2022
🏞 A simple iOS photo and video browser with optional grid view, captions and selections written in Swift5.0

Introduction ?? MediaBrowser can display one or more images or videos by providing either UIImage objects, PHAsset objects, or URLs to library assets,

Kyle Yi 631 Dec 29, 2022
Redesigned video player controls for iOS

Atlas Minimal stock video player replacement demo video Compiling Clone the repo, and make sure you have cephei and all that then just make clean pack

Chr1s 15 Feb 19, 2022
AGCircularPicker is helpful component for creating a controller aimed to manage any calculated parameter

We are pleased to offer you our new free lightweight plugin named AGCircularPicker. AGCircularPicker is helpful for creating a controller aimed to man

Agilie Team 617 Dec 19, 2022
A custom stretchable header view for UIScrollView or any its subclasses with UIActivityIndicatorView and iPhone X safe area support for content reloading. Built for iOS 10 and later.

Arale A custom stretchable header view for UIScrollView or any its subclasses with UIActivityIndicatorView support for reloading your content. Built f

Putra Z. 43 Feb 4, 2022