This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
Hey everyone. Hope you all are well. I am working on integrating saving media to camera roll functionality into a social media app similar to how Twitter/X does it. I already got image saving and GIF saving down via PHPhotoLibrary
, but I am having trouble doing the same for video saving. Whenever I do a similar implementation for it, I get error messages relating to converting the format of the video (the format is avc1) to mp4 as I originally was getting error codes saying the original format isn't supported. I tried to work around it by coding a converter to convert the video to mp4 format before saving as seen below:
extension PostViewModel {
func getPostType(post: PostOBJ) -> PostType {
return .none
}
func videoFormatConverter(videoURL: URL, completion: @escaping (URL?, Error?) -> Void) {
let asset = AVAsset(url: videoURL)
guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality) else {
completion(nil, NSError(domain: "", code: 500, userInfo: [NSLocalizedDescriptionKey: "Failed to create export session"]))
return
}
let outputURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("convertedVideo.mp4")
exportSession.outputFileType = .mp4
exportSession.outputURL = outputURL
exportSession.exportAsynchronously {
switch exportSession.status {
case .completed:
print("Successfully converted video to MP4 format.")
completion(outputURL, nil)
case .failed:
completion(nil, exportSession.error ?? NSError(domain: "", code: 500, userInfo: [NSLocalizedDescriptionKey: "Unknown error occurred"]))
case .cancelled:
completion(nil, NSError(domain: "", code: 500, userInfo: [NSLocalizedDescriptionKey: "Export cancelled"]))
default:
completion(nil, NSError(domain: "", code: 500, userInfo: [NSLocalizedDescriptionKey: "Unknown error occurred"]))
}
}
}
func getVideoFormat(forURL url: URL) -> String? {
let asset = AVURLAsset(url: url)
guard let track = asset.tracks(withMediaType: .video).first else {
return nil
}
let formatDescription = track.formatDescriptions.first
guard let description = formatDescription else {
return nil
}
let formatFourCC = CMFormatDescriptionGetMediaSubType(description as! CMFormatDescription)
let formatString = String(format: "%c%c%c%c",
(formatFourCC >> 24) & 0xff,
(formatFourCC >> 16) & 0xff,
(formatFourCC >> 8) & 0xff,
formatFourCC & 0xff)
return formatString
}
}
After converting the video to the intended format, it's supposed to save the video to the camera roll via PHPhotoLibrary
as seen below:
.contextMenu {
Button(action: {
guard let videoURL = URL(string: media.link.absoluteString) else {
print("Error fetching video url.")
return
}
if let format = viewModel.getVideoFormat(forURL: videoURL) {
print("Video format: \(format)")
}
viewModel.videoFormatConverter(videoURL: videoURL) { convertedURL, error in
if let convertedURL = convertedURL {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: convertedURL)
}){ success, error in
if success{
print("Video saved to camera roll!")
} else {
debugPrint("Error:\(String(describing: error))")
print("Error when saving video:\(error?.localizedDescription ?? "Unknown error")")
}
}
} else {
debugPrint("Error: \(String(describing: error))")
print("Error when converting video format: \(error?.localizedDescription ?? "Unknown error")")
}
}
}) {
Text("Save Video")
Image(systemName: "square.and.arrow.down")
}
ShareLink(item: viewModel.post.url) {
Text("Share via ...")
Image(systemName: "square.and.arrow.up")
}
}
When I attempt to perform the intended operation, I get these error codes:
"Error: Optional(Error Domain=AVFoundationErrorDomain Code=-11838 \"Operation Stopped\" UserInfo={NSLocalizedFailureReason=The operation is not supported for this media., NSLocalizedDescription=Operation Stopped, NSUnderlyingError=0x280d339c0 {Error Domain=NSOSStatusErrorDomain Code=-12109 \"(null)\"}})"
Error when converting video format: Operation Stopped
I am honestly stumped. I tried the Apple Dev forums only to get no help. Any ideas?
Subreddit
Post Details
- Posted
- 9 months ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/swift/comme...