Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert video data to NSURL

Tags:

ios

swift

I have a video I'm fetching from my server and receiving as data. I'm trying to cover the raw data into a URL so that I can use it to instantiate an AVPlayerItem and play the video on the phone. However, this code returns nil when I print "videoDataString". If I print "videoData" there is a result though. Here is my code where I try to convert, is my mistake the encoding part?

let videoDataString = NSString(data: videoData, encoding: NSUTF8StringEncoding)
let videoURL = NSURL(string: String(videoDataString))
like image 233
cb428 Avatar asked Dec 07 '25 23:12

cb428


2 Answers

First Save your Video data to a file then try to access that as a file URL. Here is an example.

 NSString *filePath = [self documentsPathForFileName:@"video.mp4"];
 NSData *videoAsData;   // your data here
 [videoAsData writeToFile:filePath atomically:YES];

 // access video as URL
 NSURL *videoFileURL =  [NSURL fileURLWithPath:filePath];


- (NSString *)documentsPathForFileName:(NSString *)name
{
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
   NSString *documentsPath = [paths objectAtIndex:0];

   return [documentsPath stringByAppendingPathComponent:name];
}

For Swift 3.0:

let filePath = self.documentsPathForFileName("video.mp4")
        let videoAsData = NSData()
        videoAsData.write(toFile: filePath, atomically: true)
        let videoFileURL = NSURL(fileURLWithPath: filePath)

func documentsPathForFileName(name: String) -> String {
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        return documentsPath.appending(name)
    }
like image 72
rushisangani Avatar answered Dec 09 '25 13:12

rushisangani


You cannot convert all strings to URL. URL is Uniform Resource Locator. That means it is a string containing the path to the file or resource in remote or local destination. If you want to keep your video data and instantiate video player with that video, first save the video data to a file, then instantiate video player with path to that file.

Use following code for this

let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
let videoURL = documentsURL.URLByAppendingPathComponent("video.mp4")//what ever your filename and extention
videoData.writeToURL(videoURL, atomically: true)

//uese videoURL to instantiate video player
like image 25
Johnykutty Avatar answered Dec 09 '25 12:12

Johnykutty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!