Check if Documents Directory Url empty - ios

In the below code I am trying to check if my Documents Directory Url is empty, so in case it's empty it will show now way or continue to do what ever I need.
Here is my code:
- (IBAction)saveVideo:(id)sender {
NSURL *vedioURL;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSLog(#"files array %#", filePathsArray);
NSString *fullpath;
for ( NSString *apath in filePathsArray )
{
fullpath = [documentsDirectory stringByAppendingPathComponent:apath];
vedioURL =[NSURL fileURLWithPath:fullpath];
}
NSLog(#"vurl %#",vedioURL);
NSURL *movieUrl = [NSURL fileURLWithPath:fullpath];
NSString *moviePath = [movieUrl path];
if (videoUrl.absoluteString.length == 0) {
NSLog(#"No way");
} else {
self.imageViewPost.image = [self generateThumbImage:moviePath];
AVPlayerItem * playeritem = [AVPlayerItem playerItemWithURL:vedioURL];
[_player replaceCurrentItemWithPlayerItem:playeritem];
[_player play];
[self clearTmpDirectory];
}
}
The app crashed and it shows Null value to my Url:
vurl (null)
2017-11-29 20:54:24.288473+0400 EasyVideo[43587:2429960] ***
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'
I hope to solve this issue.
Thanks

You can first get the data from the URL and check if it is not empty.
NSData *data = [NSData dataWithContentsOfURL:videoURL];
Here,if data is not empty you will perform the task accordingly:
if (data == nil)
{
//Do not perform the task.
}
else
{
//perform the task
}

Related

I'm unable to save or download video in document directory and play from document directory

I want to download or save youtube video in document directory and then play that video using MPMoviePlayerViewController. But I don't know why my code is not working.
I'm using this below code :
prgrma mark- download Or save
-(IBAction)onclick_download:(id)sender
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"Downloading Started");
NSString *urlToDownload = #"youtubeurl";
NSURL *url = [NSURL URLWithString:urlToDownload];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"thefile.mp4"];
//saving is done on main thread
dispatch_async(dispatch_get_main_queue(), ^{
[urlData writeToFile:filePath atomically:YES];
NSLog(#"File Saved !");
});
}
});
}
pragma mark- Play video from document directory
-(IBAction)onclick_playvideolocally:(id)sender
{
[self playvideolocally];
}
-(void)playvideolocally
{
NSURL *videoUrl;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSLog(#"files array %#", filePathsArray);
NSString *fullpath;
for ( NSString *apath in filePathsArray )
{
fullpath = [documentsDirectory stringByAppendingPathComponent:apath];
videoUrl =[NSURL fileURLWithPath:fullpath];
}
MPMoviePlayerViewController *videoPlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:videoUrl];
[self presentMoviePlayerViewControllerAnimated:videoPlayerView];
[videoPlayerView.moviePlayer play];
}
As your link you provided in url is for youtube so it is not downloaded or saved in local
Use this for youtube
Ive used classes from this project: https://github.com/larcus94/LBYouTubeView It works fine for me. I can download youtube videos.
LBYouTubeExtractor *extractor = [[[LBYouTubeExtractor alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:(#"http://www.youtube.com/watch?v=%#"), self.videoID ]] quality:LBYouTubeVideoQualityLarge] autorelease];
[extractor extractVideoURLWithCompletionBlock:^(NSURL *videoURL, NSError *error) {
if(!error) {
NSLog(#"Did extract video URL using completion block: %#", videoURL);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL: videoURL];
NSString *pathToDocs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filename = [NSString stringWithFormat:(#"video_%#.mp4"), self.videoID ];
[data writeToFile:[pathTODocs stringByAppendingPathComponent:filename] atomically:YES];
NSLog(#"File %# successfully saved", filename);
});
} else {
NSLog(#"Failed extracting video URL using block due to error:%#", error);
}
}];

How to save multiple videos into application document directory?

I am using GMImagePicker to fetch assets of camera roll.
After selecting single or multiple videos i got PHAsset in arrayArray.
assetArray data in this formate
"<PHAsset: 0x7fe0e8f21130> 40D4733D-4C7B-443D-8093-C28E39ACA45E/L0/001 mediaType=2/0, sourceType=1, (720x480), creationDate=2016-02-14 09:50:58 +0000, location=0, hidden=0, favorite=0 "
How can i store this video into my application document directory?
The code i did to store video is
for (PHAsset *asset in assetArray) {
if (asset.mediaType==PHAssetMediaTypeVideo) {
NSLog(#"Video found");
}
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
options.version = PHVideoRequestOptionsVersionOriginal;
[[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
if ([asset isKindOfClass:[AVURLAsset class]]) {
NSURL *URL = [(AVURLAsset *)asset URL];
NSMutableData *responseData=[[NSMutableData alloc] init];
responseData = [NSMutableData dataWithContentsOfURL:URL];
if (responseData.length>0) {
NSString * lastPath = [URL.absoluteString lastPathComponent];//videoname.mp4
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#",docDirPath,lastPath];
[responseData writeToFile:filePath atomically:YES];
}
}];
}
I also checked filepath where video is saved. Video is available but i get this error.
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
Please help me to solve this.
According to me use NSMutableData instead of NSData it's accept Nullable value
self.responseData = [NSMutableData dataWithContentsOfURL:location];
if (self.responseData.length>0) {
dispatch_async(dispatch_get_main_queue(), ^{
NSString * lastPath = [url.absoluteString lastPathComponent];//videoname.mp4
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#",docDirPath,lastPath];
[self.responseData writeToFile:filePath atomically:YES];
}
});
hope this help you.
For storing both Images And Video
for (PHAsset *asset in assetArray) {
if (asset.mediaType==PHAssetMediaTypeVideo) {
NSLog(#"Video found");
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
options.version = PHVideoRequestOptionsVersionOriginal;
[[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
if ([asset isKindOfClass:[AVURLAsset class]]) {
NSURL *URL = [(AVURLAsset *)asset URL];
[Albumvideos addObject:URL];
NSData *videoData = [NSData dataWithContentsOfURL:URL];
if (videoData.length>0) {
NSString *lastPath = [URL.absoluteString lastPathComponent];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#-%#",TimeStamp,lastPath]];
[fileManager createFileAtPath:fullPath contents:videoData attributes:nil];
}
}
}];
}
else{
self.requestOptions = [[PHImageRequestOptions alloc] init];
self.requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
self.requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
// this one is key
self.requestOptions.synchronous = true;
// self.assets = [NSMutableArray arrayWithArray:assets];
PHImageManager *manager = [PHImageManager defaultManager];
// assets contains PHAsset objects.
__block UIImage *ima;
// Do something with the asset
[manager requestImageForAsset:asset
targetSize:PHImageManagerMaximumSize
contentMode:PHImageContentModeDefault
options:self.requestOptions
resultHandler:^void(UIImage *image, NSDictionary *info) {
ima = image;
[Albumimages addObject:ima];
}];
}
}
Albumvideos is mutable array which contain video URL and Albumimages contain selected images.

UIDocumentInteractionController "invalid scheme (null)"

I'm trying to preview a document with UIDocumentInteractionController.
The document is an .xls file which my app downloads from the web. I keep getting this error:
'UIDocumentInteractionController: invalid scheme (null). Only the file scheme is supported.'
I use the next code:
- (void) webServiceController:(WebServiceController *)webServiceController returnedArray:(NSMutableArray *)array {
if ([webServiceController.webRequest isEqualToString: #"generateExcelFileForEmployee"]) {
// start previewing the document at the current section index
NSString *link = [[NSString stringWithString:array[0]] stringByReplacingOccurrencesOfString:#"AdminFunctions.php" withString:#"AdminFunctions.xls"];
link = [[[link stringByReplacingOccurrencesOfString:#"\\" withString:#""]stringByReplacingOccurrencesOfString:#"/public/sites/" withString:#"http://"]stringByReplacingOccurrencesOfString:#"\"\\\"" withString:#""];
NSLog(#"%#", link);
NSData *urlData = [NSData dataWithContentsOfURL:[NSURL URLWithString:link]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"AdminFunctions.xls"];
BOOL isWriteSuccess = [urlData writeToFile:filePath atomically:YES];
NSLog(#"%#", filePath);
if(isWriteSuccess) //success
{
file = [NSURL fileURLWithPath:filePath];
self.fileView = [self setupControllerWithURL:file usingDelegate:self];
[self.fileView presentPreviewAnimated:YES];
}
else
{
NSLog(#"file not written");
}
}
}
- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
UIDocumentInteractionController *interactionController =
[UIDocumentInteractionController interactionControllerWithURL: fileURL];
interactionController.delegate = interactionDelegate;
return interactionController;
}
- (UIViewController *) documentInteractionControllerViewControllerForPreview: (UIDocumentInteractionController *) controller {
return self;
}
Both methods are implemented in the viewcontroller in which I want to present the preview. I know by hard i'm getting the data in the urlData object, because when I put in breakpoints, the console says that it contains 6144 bytes, which is exactly the size of the document to download.
I have been looking for this for quiet a while now, but I can't seem to figure out how to solve this. I already tried putting in the link object as a source for the documentInteractionController, but then the error changes to:
'UIDocumentInteractionController: invalid scheme (http). Only the file scheme is supported.'
Any comments on how I can overcome this issue would be highly appreciated
Try to use
// objC
file = [NSURL fileURLWithPath:filePath];
// swift
file = URL.init(fileURLWithPath: filePath)
instead of
//objC
file = [NSURL URLWithString:filePath];
// swift
file = URL.init(string: filePath)

Load the resource after downloading(ios)

I am downloading the resources from server and writing it to the documents directory successfully by using this code below
NSString *fileName = [[[NSURL URLWithString:url] path] lastPathComponent];
NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [pathArr objectAtIndex:0];
NSString *filePath = [folder stringByAppendingPathComponent:fileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSLog(#"File written");
NSError *writeError = nil;
[webData writeToURL: fileURL options:0 error:&writeError];
if( writeError) {
NSLog(#" Error in writing file %#' : \n %# ", filePath , writeError );
return;
}
NSLog(#"%#",fileURL);
Now I want to access those files to use it.I have tried this code
-(UIImage *) loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath
{
UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/%#.%#", directoryPath, fileName, extension]];
return result;
}
Now method used is like this:
UIImage *imageFromWeb = [self loadImage:#"metaioman" ofType:#"png" inDirectory:folder];
_imgview.image=imageFromWeb;
But no luck...please help
Thank you
Firstly check file exists using NSFileManager.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *pathForFile = [NSString stringWithFormat:#"%#/%#.%#", directoryPath, fileName, extension]
UIImage * result = nil;
if ([fileManager fileExistsAtPath:pathForFile]){
//file exists
result = [UIImage imageWithContentsOfFile:pathForFile];
}
else
{
//file doesnot exists or wrong filename.
}
return result;
Reference : http://beageek.biz/save-and-load-uiimage-in-documents-directory-on-iphone-xcode-ios/

Converting NSData to NSUrl nil string parameter

I am trying to convert NSdata to NSUrl, and I found this method on the internet:
NSString *urlString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
NSURL *url = [[NSURL alloc] initWithString:urlString];
[session sendResourceAtURL:url withName:#"Resource" toPeer:peerID withCompletionHandler:nil];
Seems all right to me, but the app crashes at the second line and gives the error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initWithString:relativeToURL:]: nil string parameter'
Can't get why...
myData is not UTF-8 encoded.
From the NSString docs:
Returns nil if the initialization fails for some reason (for example
if data does not represent valid data for encoding).
You should always check for this type of condition...
NSString *urlString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
NSURL *url;
if (urlString) {
url = [[NSURL alloc] initWithString:urlString];
} else {
// handle failure
}
Additionally, make sure you're using UTF8 encoding when you create the myData object, or switch from NSUTF8StringEncoding to the correct encoding type.
If dict from [NSKeyedArchiver archivedDataWithRootObject:dict] is NSDictionary class then you must extract the urlString from that dictionary.
NSError* error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSString *urlString = [dictionary valueForKey:#"url"];
change the encoding, say to NSUTF16StringEncoding
your String returns null try these method
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:#".png"];
[fileManager createFileAtPath:fullPath contents:myData attributes:nil];
if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath])
{
NSURL *imageUrl = [NSURL fileURLWithPath:fullPath isDirectory:NO];
}

Resources