Last active
November 6, 2023 06:46
-
-
Save robertmryan/58afba63a74bf68e976793a911533e4e to your computer and use it in GitHub Desktop.
Export MPMediaItem to file in Documents
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Export MPMediaItem to temporary file. | |
/// | |
/// - Parameters: | |
/// - assetURL: The `assetURL` of the `MPMediaItem`. | |
/// - completionHandler: Closure to be called when the export is done. The parameters are a boolean `success`, the `URL` of the temporary file, and an optional `Error` if there was any problem. The parameters of the closure are: | |
/// | |
/// - fileURL: The `URL` of the temporary file created for the exported results. | |
/// - error: The `Error`, if any, of the asynchronous export process. | |
func export(_ assetURL: URL, completionHandler: @escaping (_ fileURL: URL?, _ error: Error?) -> ()) { | |
let asset = AVURLAsset(url: assetURL) | |
guard let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) else { | |
completionHandler(nil, ExportError.unableToCreateExporter) | |
return | |
} | |
let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()) | |
.appendingPathComponent(NSUUID().uuidString) | |
.appendingPathExtension("m4a") | |
exporter.outputURL = fileURL | |
exporter.outputFileType = "com.apple.m4a-audio" | |
exporter.exportAsynchronously { | |
if exporter.status == .completed { | |
completionHandler(fileURL, nil) | |
} else { | |
completionHandler(nil, exporter.error) | |
} | |
} | |
} | |
func exampleUsage(with mediaItem: MPMediaItem) { | |
if let assetURL = mediaItem.assetURL { | |
export(assetURL) { fileURL, error in | |
guard let fileURL = fileURL, error == nil else { | |
print("export failed: \(error)") | |
return | |
} | |
// use fileURL of temporary file here | |
print("\(fileURL)") | |
} | |
} | |
} | |
enum ExportError: Error { | |
case unableToCreateExporter | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Question posted in comments to http://stackoverflow.com/questions/37397581/how-add-int-vaue-to-the-alamofire-upload-parameters/37397828#comment69244352_37397828
Adapted from http://stackoverflow.com/a/40929355/1271826