Skip to content

Commit

Permalink
Prevent a crash when the data is released to early (#124)
Browse files Browse the repository at this point in the history
  • Loading branch information
BowdusBrown authored and sindresorhus committed Aug 15, 2019
1 parent 6f6bf34 commit 2ec78f3
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions Gifski/Gifski.swift
Expand Up @@ -46,6 +46,9 @@ final class Gifski {
}
}

// This is carefully nil'd and should remain private.
private static var gifData: NSMutableData?

// TODO: Split this method up into smaller methods. It's too large.
/**
Converts a movie to GIF
Expand All @@ -56,6 +59,8 @@ final class Gifski {
var progress = Progress(parent: .current())

let completionHandlerOnce = Once().wrap { (_ result: Result<Data, Error>) -> Void in
gifData = nil // Resetting state

DispatchQueue.main.async {
guard !progress.isCancelled else {
completionHandler?(.failure(.cancelled))
Expand Down Expand Up @@ -85,7 +90,7 @@ final class Gifski {
return progress.isCancelled ? 0 : 1
}

var gifData = NSMutableData()
gifData = NSMutableData()

gifski.setWriteCallback(context: &gifData) { bufferLength, bufferPointer, context in
guard
Expand Down Expand Up @@ -184,7 +189,8 @@ final class Gifski {
if result.isFinished {
do {
try gifski.finish()
completionHandlerOnce(.success(gifData as Data))
// Force unwrapping here is safe because we nil gifData in one single place after this.
completionHandlerOnce(.success(gifData! as Data))
} catch {
completionHandlerOnce(.failure(.writeFailed(error)))
}
Expand Down

0 comments on commit 2ec78f3

Please sign in to comment.