我正在开发一个在服务器上上传录制视频的应用,但它必须以多个部分发送,这些部分编码为base64。
如何使用swift将视频拆分/剪切为多个部分?
答案 0 :(得分:1)
首先转换为NSData
然后将该数据划分为不同的不同块,然后使用发送到服务器端的base64将该块分成encode
。
现在,以下是相同的示例代码。
import UIKit
import MobileCoreServices
import Foundation
extension String {
var ns: NSString {
return self as NSString
}
var pathExtension: String? {
return ns.pathExtension
}
var lastPathComponent: String? {
return ns.lastPathComponent
}
}
// MARK: - Mixed string utils and helpers
extension String {
/**
Encode a String to Base64
:returns:
*/
func toBase64()->String{
let data = self.dataUsingEncoding(NSUTF8StringEncoding)
return data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
}
}
class ViewController: UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet var img:UIImageView!=nil
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
@IBAction func buttonTapped()
{
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)
{
// print("Camera Available")
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
imagePicker.allowsEditing = false
imagePicker.mediaTypes = [kUTTypeMovie as String]
self.presentViewController(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
dismissViewControllerAnimated(true, completion: nil)
let videoUrl = info[UIImagePickerControllerMediaURL] as! NSURL!
let pathString = videoUrl.relativePath
print(pathString)
let videoDataURL = info[UIImagePickerControllerMediaURL] as! NSURL!
let videoFileURLs = videoDataURL.filePathURL
let chunkSize : Int = 2*1024*1024 // 2 MB
do {
let videoData = try NSData(contentsOfURL: videoFileURLs!, options: .DataReadingMappedIfSafe)
var newFileName = pathString!.pathExtension
let totalSizeOfBase64 : Int = Int(videoData.length)
for var chunksWritten :Int = 0; chunksWritten * chunkSize < totalSizeOfBase64; chunksWritten++
{
let modifiedURLString = NSString(format:" %03lu.MOV", chunksWritten) as String
newFileName = newFileName!+modifiedURLString
let rangeValue = NSMakeRange(chunksWritten * chunkSize, min(chunkSize, totalSizeOfBase64 - chunksWritten * chunkSize))
let finalString = videoData.subdataWithRange(rangeValue)
//Encoding Base64
let base64String = finalString.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
print("\(base64String)")
// print("\(newFileName)")
newFileName = pathString!.pathExtension
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
这可能会有所帮助。