9

Thus far I have the following

  let assetUrl = NSURL.URLWithString(self.targetVideoString)
  let asset: AVAsset = AVAsset.assetWithURL(assetUrl) as AVAsset
  let imageGenerator = AVAssetImageGenerator(asset: asset);
  let time : CMTime = CMTimeMakeWithSeconds(1.0, 1)
  let actualTime : CMTime
  let myImage: CGImage =imageGenerator.copyCGImageAtTime(requestedTime: time, actualTime:actualTime, error: <#NSErrorPointer#>)

The last line is where I get lost ... I simply want to grab an image at time 1.0 seconds

Craig
  • 9,335
  • 2
  • 34
  • 38
user379468
  • 3,989
  • 10
  • 50
  • 68

4 Answers4

20

The function is declared as

func copyCGImageAtTime(requestedTime: CMTime, actualTime: UnsafeMutablePointer<CMTime>, error outError: NSErrorPointer) -> CGImage!

and you have to pass (initialized) CMTime and NSError? variables as "in-out expression" with &:

let assetUrl = NSURL(string: ...)
let asset: AVAsset = AVAsset.assetWithURL(assetUrl) as AVAsset
let imageGenerator = AVAssetImageGenerator(asset: asset);
let time = CMTimeMakeWithSeconds(1.0, 1)

var actualTime : CMTime = CMTimeMake(0, 0)
var error : NSError?
let myImage = imageGenerator.copyCGImageAtTime(time, actualTime: &actualTime, error: &error)

Note also that your first line

let assetUrl = NSURL.URLWithString(self.targetVideoString)

does not compile anymore with the current Xcode 6.1.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
6

With Swift2.0 imageGenerator.copyCGImageAtTime is now marked with throws so you have to handle the errors in a do - try - catch block.

    let asset : AVAsset = AVAsset(URL: yourNSURLtoTheAsset )
    let imageGenerator = AVAssetImageGenerator(asset: asset)
    let time = CMTimeMakeWithSeconds(0.5, 1000)
    var actualTime = kCMTimeZero
    var thumbnail : CGImageRef?
    do {
        thumbnail = try imageGenerator.copyCGImageAtTime(time, actualTime: &actualTime)
    }
    catch let error as NSError {
        print(error.localizedDescription)
    }
Tim Bull
  • 2,375
  • 21
  • 25
4

Accepted answer in Swift 3, 4:

let asset = AVURLAsset(url: URL(fileURLWithPath: "YOUR_URL_STRING_HERE"))
let imgGenerator = AVAssetImageGenerator(asset: asset)
var cgImage: CGImage?
do {
    cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil)
} catch let error as NSError {
    // Handle the error
    print(error)
}
// Handle the nil that cgImage might be
let uiImage = UIImage(cgImage: cgImage!)
Allen
  • 2,979
  • 1
  • 29
  • 34
  • Can this be used to capture at the current time of a video vs just setting a manual second to capture it at? – Luke Irvin Nov 11 '19 at 19:29
2

As of at least Xcode 7.0.1 and Swift 2 assetwithURL is now: let asset = AVAsset(URL: assetURL). Xcode error was "'assetWithURL' is unavailable: use object construction 'AVAsset(URL:)'"

Amelia
  • 185
  • 2
  • 9