need to convert a video file to NSData and then back to playable URL. The NSData portion is as follows:
let videoNSD = NSData(contentsOfURL: videoPreview!)
// videoNSD is uploaded to cloud and then retrieved..
func playNSDataVideoPreview(videoNSD: NSData)
{
// how to play in AVPlayer?
let playerController = AVPlayerViewController()
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
let filePath = documentsDirectory + "/" + "nsdfile-1234.mp4"
let nsdURL = NSURL(fileURLWithPath: filePath)
videoNSD.writeToURL(nsdURL, atomically: true)
mediaPlayer = AVPlayer(URL: nsdURL)
playerController.player = mediaPlayer
mediaPlayer.play()
}
What is the best practice for playing in AVPlayer?
Thanks...
First of all, I'd suggest to Upload/Download as file ( from File handle ) and not Data ( NSData ) , because videos might be bigger than RAM ( imagine a movie ).
To download File with Alamofire , you can use sample code from https://github.com/Alamofire/Alamofire#downloading
Alamofire.download(.GET, "http://httpbin.org/stream/100") { temporaryURL, response in
let fileManager = NSFileManager.defaultManager()
let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let pathComponent = response.suggestedFilename
return directoryURL.URLByAppendingPathComponent(pathComponent!)
}
after downloading and having a file, you can directly use AVPlayer(URL URL: NSURL)
If you have just NSData of video and want to play it, first save it as file and then create AVPlayer with your saved URL ( file location )
YOURVIDEODATA.writeToURL(URL_WHERE_TO_SAVE,atomically: true)
and then again use AVPlayer(URL: URL_WHERE_TO_SAVE)
Related
I have used the below implementation to play a video with cookies content from the server, but it shows play icon with cross line. I have refer the link and do following implementation in swift. but I didn't get any output :(
func showVideo(url: String) {
let videoURL = NSURL(string: url)
var cookiesArray = [HTTPCookie]()
guard let cookieArray = UserDefaults.standard.array(forKey:
Constants.Object.kCookie) as? [[HTTPCookiePropertyKey: Any]] else {
return }
for cookieProperties in cookieArray {
if let cookie = HTTPCookie(properties: cookieProperties) {
cookiesArray.append(cookie)
}
}
let cookieArrayOptions = [AVURLAssetHTTPCookiesKey: cookiesArray]
let assets = AVURLAsset(url: videoURL! as URL, options: cookieArrayOptions)
let item = AVPlayerItem(asset: assets)
videoPlayer = AVPlayer(playerItem: item)
self.playerController.player = self.videoPlayer
self.playerController.view.frame = self.view.frame
self.present(self.playerController, animated: true, completion: nil)
self.playerController.player?.play()
}
Please help me on that, what is wrong in that implementation.
Thanks in advance! :)
After going through so many ways finally I have got the solution which worked for me :
func showVideo(url: String) {
let videoURL = NSURL(string: url)
let cookiesArray = HTTPCookieStorage.shared.cookies! //Stored Cookies of your request
let values = HTTPCookie.requestHeaderFields(with: cookiesArray)// Returns a dictionary of header fields corresponding to a provided array of cookies.ex.["Cookie":"your cookies values"]
let cookieArrayOptions = ["AVURLAssetHTTPHeaderFieldsKey": values]
let assets = AVURLAsset(url: videoURL! as URL, options: cookieArrayOptions)
let item = AVPlayerItem(asset: assets)
videoPlayer = AVPlayer(playerItem: item)
self.playerController.player = self.videoPlayer
self.playerController.view.frame = self.view.frame
self.present(self.playerController, animated: true, completion: nil)
self.playerController.player?.play()
}
How can I fix the
init(URL:) has been renamed to init(url:)
error in my Xcode 8 project?
This is my code:
override func viewDidLoad() {
super.viewDidLoad()
// Load the video from the app bundle.
let videoURL: NSURL = Bundle.main.url(forResource: "IMG_4628", withExtension: "mp4")! as NSURL
player = AVPlayer (URL: videoURL)
player?.actionAtItemEnd = .none
player?.isMuted = true
let playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
playerLayer.zPosition = -1
playerLayer.frame = view.frame
view.layer.addSublayer(playerLayer)
player?.play()
//loop video
How can I fix the error in the line player = AVPlayer(URL: videoURL)?
Thanks.
You should replace the uppercased URL with url in the initializer.
player = AVPlayer(url: videoURL)
just replace with the following code.
player = AVPlayer(url : videoURL! as URL)
Here's the code for a 'selection' button, where it passes the NSData to the global variable to be used later.
#IBAction func btnCCTV1(_ sender: Any) {
// Put Your Image URL
let url:NSURL = NSURL(string : "http://cctv-sg.com/images/sr/01.jpg")!
// It Will turn Into Data
let imageData : NSData = NSData.init(contentsOf: url as URL)!
// Data Will Encode into Base64
let str64 = imageData.base64EncodedData(options: .lineLength64Characters)
// Now Base64 will Decode Here
let data: NSData = NSData(base64Encoded: str64 , options: .ignoreUnknownCharacters)!
// turn Decoded String into Data
let dataImage = UIImage(data: data as Data)
// pass the data image to image View.:)
viewImage.image = dataImage
print("====64====")
print (str64)
print(imageData)
GlobalVar.data64 = imageData as NSData
GlobalVar.imageByte=dataImage
}
Inserting the images to the SQLite
#IBAction func btnSave(_ sender: Any) {
let imageDB = FMDatabase(path: databasePath as String)
print("==image====")
// print(GlobalVar.imageByte)
if (imageDB?.open())! {
let insertSQL = "INSERT INTO ImagesDB (images, photo) VALUES ('\(images)', '\(GlobalVar.data64)')"
let result = contactDB?.executeUpdate(insertSQL,
withArgumentsIn: nil)
if !result! {
lblResult.text = "Failed to add images"
print("Error: \(imageDB?.lastErrorMessage())")
} else {
lblResult.text = "Images Added"
}
} else {
print("Error: \(imageDB?.lastErrorMessage())")
}
}
How do I make the images just insert to SQLiteDB only? I am complete newbie in Swift 3, so having trouble to insert the images into the SQLite. Any suggestion or help is appreciated. If there are any similar swift 3 code which are able to insert images into SQLite without using FMDatabase is fine too.
//GET text FROM SERVER
let requestText = NSMutableURLRequest(url: URL(string: "Http://a.txt")!, ...)
let sessionText = URLSession.shared
let downloadText = sessionText.dataTask(with: requestText as URLRequest) {data,response,error in
......
}
DispatchQueue.main.async {
//Update your UI here
}
}//dataTask
downloadText.resume()
//GET pic FROM SERVER
let requestText = NSMutableURLRequest(url: URL(string: "Http://a.jpg")!, ...)
let sessionPic = URLSession.shared
let downloadPic = sessionPic.dataTask(with: requestText as URLRequest) {data,response,error in
......
}
DispatchQueue.main.async {
//Update your UI here
}
}//dataTask
downloadPic.resume()
Hi, am not an expert in swift but I have a page the I would like to download pic (into UIImageView) and text (into UITextView) from a server. If I have multiple pics and text, must I run multiple session, request and Task.resume(), DispatchQueue.main.async ?
Is there way to get multiple request doing a single xxxx.resume()?
Thank you
I have a downloader class that downloads a file based on a given URL which then calls a completion passing it the contents of the file as NSData.
For the project that I'm using this in, the URL will be a JPEG image. The downloader works perfectly; I can use the result into NSImage and show it in a Image View Controller.
I would like to be able to save that NSData object to file.
After quite some time researching the internet on Google, StackOverflow, etc. and trying many suggestions, I cannot get the file to save.
Here is a playground of the Downloader class and my attempt to save the file:
//: Playground - noun: a place where people can play
import Cocoa
class NetworkService
{
lazy var configuration: URLSessionConfiguration = URLSessionConfiguration.default
lazy var session: URLSession = URLSession(configuration: self.configuration)
let url: NSURL
init(url: NSURL)
{
self.url = url
}
func downloadImage(completion: #escaping ((NSData) -> Void))
{
let request = NSURLRequest(url: self.url as URL)
let dataTask = session.dataTask(with: request as URLRequest) { (data, response, error) in
if error == nil {
if let httpResponse = response as? HTTPURLResponse {
switch (httpResponse.statusCode) {
case 200:
if let data = data {
completion(data as NSData)
}
default:
print(httpResponse.statusCode)
}
}
} else {
print("Error download data: \(error?.localizedDescription)")
}
}
dataTask.resume()
}
}
let IMAGE_URL = NSURL(string: "https://www.bing.com/az/hprichbg/rb/RossFountain_EN-AU11490955168_1920x1080.jpg")
let networkService = NetworkService(url: IMAGE_URL!)
networkService.downloadImage(completion: { (data) in
data.write(to: URL(string: "file://~/Pictures/image.jpg")!, atomically: false)
})
The playground console show nothing at all. Can anyone spot why its not working?
NOTE: The target is macOS, not iOS. Also, I'm a swift noob...
I did try this:
networkService.downloadImage(completion: { (imageData) in
let imageAsNSImage = NSImage(data: imageData as Data)
if let bits = imageAsNSImage?.representations.first as? NSBitmapImageRep {
let outputData = bits.representation(using: .JPEG, properties: [:])
do {
try outputData?.write(to: URL(string: "file://~/Pictures/myImage.jpg")!)
} catch {
print("ERROR!")
}
}
})
It could be a permission issue. You may try:
let picturesDirectory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask)[0]
let imageUrl = picturesDirectory.appendingPathComponent("image.jpg", isDirectory: false)
try? data.write(to: imageUrl)
It does work for me: