I need to determine what file type a file is and then perform a certain action for it. this seems to work fine for some types, however all media types such as videos and sound files get mixed up. I determine the file type by doing this:
BOOL matchedMP3 = ([[rowValue pathExtension] isEqualToString:#"mp3"]);
if (matchedMP3 == YES)
{
NSLog(#"Matched MP3");
}
I do this for various file types and just define an "else" for all the others. Here's the problem though. The iPhone calls them both. Here's what the log reveals:
2010-05-11 18:51:12.421 Test [5113:207] Matched MP3
2010-05-11 18:51:12.449 Test [5113:207] Matched ELSE
I've never seen anything like this before.
This is my "matchedMP3" function:
BOOL matchedMP3 = ([[rowValue pathExtension] isEqualToString:#"mp3"]);
if (matchedMP3 == YES)
{
NSLog(#"Matched MP3");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
self.directoryContent = [manager directoryContentsAtPath:documentsDirectory];
NSString *errorMessage = [documentsDirectory stringByAppendingString:#"/"];
NSString *urlAddress = [errorMessage stringByAppendingString:rowValue];
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:urlAddress]];
moviePlayer.movieControlMode = MPMovieControlModeDefault;
moviePlayer.backgroundColor = [UIColor blackColor];
[moviePlayer play];
}
and here's the else statement:
else {
NSLog(#"Matched ELSE");
[[NSUserDefaults standardUserDefaults] setObject:rowValue forKey:#"rowValue"];
NSString*rowValue = [[NSUserDefaults standardUserDefaults] objectForKey:#"rowValue"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
self.directoryContent = [manager directoryContentsAtPath:documentsDirectory];
NSString *errorMessage = [documentsDirectory stringByAppendingString:#"/"];
NSString *urlAddress = [errorMessage stringByAppendingString:rowValue];
webViewHeader.prompt = rowValue;
[documentViewer setDelegate:self];
NSString *encodedString = [urlAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//Create a URL object.
NSURL *url = [NSURL URLWithString:encodedString];
//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[documentViewer loadRequest:requestObj];
[navigationController pushViewController:webView animated:YES];
}
I can't see a reason why it wouldn't work. What happens is that both the webview and the MediaPlayer toggle their own player, so they overlap and play their sound/video a few secs apart from each other.
Any help would be appreciated & thank for you taking the time to read through my code.
Didn't you mistakenly do something like
if(conditionA)
{
...
}
if(conditionB)
{
...
}
else
{
....
}
In this case, if conditionA is satisfied but conditionB is not, the else clause is executed, because the first if clause finishes at the second if. You would want
if(conditionA)
{
...
}
else if(conditionB)
{
...
}
else
{
....
}
instead. Beware the else if.
By the way, you don't have to and shouldn't compare a BOOL against YES.
if(matchedMP3)
is enough. Remember, if accepts a boolean expression inside. A boolean value is a boolean expression!
Related
In my application i store my video in document directory with name is 'video2.MOV' and i want to play it.
Here problem is that i am not able to get this video (name is 'video2.MOV') from document directory.
My Code :
-(void)playVideo:(NSTimer *)theTimer
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"video2.MOV"];
NSLog(#"filePath - %#",filePath);
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"contentPath - %#",content);
MPMoviePlayerViewController *videoPlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:content]];
[[CCDirector sharedDirector] presentMoviePlayerViewControllerAnimated:videoPlayerView];
[videoPlayerView.moviePlayer play];
}
In console, each time i got contentPath is NULL, so may be i am not able to play video.
Here, What is my mistake. please give me suggestion on this issue.
Try this:
- (NSString*)GetDocumentFilePath:(NSString*)filename
{
NSLog(#"%#",filename);
// NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString* file = [[NSString alloc]initWithFormat:#"%#",filename];
NSString* path = [documentsDirectory stringByAppendingPathComponent:file];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4
{
//NSString *bundle = [[NSBundle mainBundle] pathForResource:filename ofType:#"plist"]; //5
//[fileManager copyItemAtPath:bundle toPath:path error:&error]; //6
}
return path;
}
and get file path like this:
NSURL *URL = [NSURL fileURLWithPath:[self GetDoucmentPath:path]];
MPMoviePlayerController* theMovie=[[MPMoviePlayerController alloc] initWithContentURL:pptURL];
theMovie.scalingMode=MPMovieScalingModeAspectFill;
theMovie.view.frame = CGRectMake(60, 20, 700, 500);
theMovie.view.center = self.view.center;
//[self.view addSubview:theMovie.view];
// Register for the playback finished notification.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(onStop)
name:MPMoviePlayerPlaybackDidFinishNotification
object:theMovie];
// Movie playback is asynchronous, so this method returns immediately.
[self.view addSubview:theMovie.view];
[theMovie play];
Hope it Helps!!
Instead of using content use filePath instead to get to the movie file:
MPMoviePlayerViewController *videoPlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:filePath]];
I am using following code to download an slqite file and storing it
self.responseData = NSMutableData
I receive responseData = 2048bytes. working well.
However white writing it does create a file myFile.sqlite but it is of Zero bytes.
What is wrong?
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success)
{
if(self.responseData)
{
dbPath = [dbPath stringByAppendingPathComponent:[self.selectedBtn.dbPath lastPathComponent]];
[self.responseData writeToFile:dbPath atomically:YES];
[self performSegueWithIdentifier:#"list" sender:self];
}
}
[self.alertView removeFromSuperview];
}
-(NSString *) getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSURL *url = [[NSURL alloc] initWithString:[self.selectedBtn.dbPath lastPathComponent]];
return [documentsDir stringByAppendingPathComponent:[url lastPathComponent]];
}
I am getting error
`The operation couldn’t be completed. (Cocoa error 4.)`
dbPath : /Users/umar/Library/Application Support/iPhone Simulator/6.1/Applications/00027635-CE9C-48C3-8000-64CA1E6532F1/Documents/music.sqlite/music.sqlite
You are appending [self.selectedBtn.dbPath lastPathComponent] twice, once in getDBPath, and again ion connctionDidFinishLoading.
Pick one of those instances to remove.
Documents/music.sqlite/music.sqlite
Nah, this is not a valid path... You meant Documents/music.sqlite, didn't you? Also, I don't see why you're raping poor NSURL for an unrelated task.
return [documentsDir stringByAppendingPathComponent:[self.selectedBtn.dbPath lastPathComponent]];
Also, make sure self.selectedBtn.dbPath also is indeed a valid path and not junk (I could imagine it is).
I have an issue where I'm trying to view a document (Word document, image, or video) that I have stored locally. I'm using UIWebView and on the Simulator it works perfectly, but on the device, it's a blank screen (no errors thrown in console). Here's my code to view the document:
UIWebView *newWebView;
if (appDelegate.IS_IPAD)
{
newWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 768, 1024)];
}
else
{
newWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
}
newWebView.scalesPageToFit = YES;
[self setWebView: newWebView];
[newWebView release], newWebView = nil;
[[self webView] setDelegate: self];
[[self view] addSubview:[self webView]];
NSURL *nsURL = [NSURL fileURLWithPath:filePath isDirectory:NO];
[[self webView] loadRequest:[NSURLRequest requestWithURL:nsURL]];
Here's how I'm saving the document locally before viewing. I do think the file is getting successfully saved on the device as it does on the simulator.
// Save the file on the device
NSURL *contentUrl = [NSURL URLWithString:selectedContent.contentUrl];
NSString *fileName = [[contentUrl absoluteString] lastPathComponent];
NSString *homeDirectoryPath = NSHomeDirectory(); // Create the path
NSString *unexpandedPath = [homeDirectoryPath stringByAppendingString:#"/MyApp/"];
NSString *folderPath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedPath stringByExpandingTildeInPath]], nil]];
NSString *unexpandedImagePath = [folderPath stringByAppendingFormat:#"/%#", fileName];
NSString *filePath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedImagePath stringByExpandingTildeInPath]], nil]];
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:NULL])
{
[[NSFileManager defaultManager] createDirectoryAtPath:nil withIntermediateDirectories:NO attributes:nil error:nil];
}
// Do the actual write of the file to the device
NSData *fileData = [NSData dataWithContentsOfURL:myUrl]; // Create the file data reference
[fileData writeToFile:filePath atomically:YES]; //Save the document to the home directory
Watch out for case issues. The simulator is not case sensitive whereas the iPhone is!
I solved this by saving my document to the default Documents Directory. Here's the code I used to accomplish this:
NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [arrayPaths objectAtIndex:0];
NSString *filePath = [docDirectory stringByAppendingString:#"/"];
filePath = [filePath stringByAppendingString:fileName];
NSData *fileData = [NSData dataWithContentsOfURL:myUrl];
[fileData writeToFile:filePath atomically:YES];
I am trying to check whether a plist exists in my doc folder: if yes, load it, if not load from resource folder.
- (void)viewWillAppear:(BOOL)animated
{
//to load downloaded file
NSArray *docpaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [docpaths objectAtIndex:0];
NSString *docpath = [documentsDirectory stringByAppendingPathComponent:#"downloadedfile.plist"];
//if document folder got file
if(docpath != nil)
{
NSDictionary *dict = [[NSDictionary alloc]
initWithContentsOfFile:docpath];
self.allNames = dict;
[dict release];
}
//on error it will try to read from disk
else {
NSString *path = [[NSBundle mainBundle] pathForResource:#"resourcefile"
ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc]
initWithContentsOfFile:path];
self.allNames = dict;
[dict release];
}
[table reloadData];
Where did I go wrong? The plist is not loading from resource folder.
I think if you create an instance of NSFileManager you can then use the file exists method
BOOL exists;
NSFileManager *fileManager = [NSFileManager defaultManager];
exists = [fileManager fileExistsAtPath:docPath];
if(exists == NO)
{
// do your thing
}
You need to check wether the file exists in your Documents folder (with NSFileManager or something like this). stringByAppendingPathComponent: doesn’t care wether the path it returns exists or is valid.
I have used a similar approach in one of the applications and it was working fine for me. Where at the launch of the application, I check for the plist file inside the document directory and if it does not exists there, then it is copied from the resource folder.
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString * plistName = #"FlowerList";
NSString * finalPath = [basePath stringByAppendingPathComponent:
[NSString stringWithFormat: #"%#.plist", plistName]];
NSFileManager * fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:finalPath])
{
NSError *error;
NSString * sourcePath = [[NSBundle mainBundle] pathForResource:#"FlowerList" ofType:#"plist"];
[fileManager copyItemAtPath:sourcePath toPath:finalPath error:&error];
}
Here is the Swift version of Chris's Answer:
if (NSFileManager.defaultManager().fileExistsAtPath(path)) {
// ...
}
My writeToFile is not saving my data to my .plist.
- (IBAction)clickBtnDone:(id) sender {
NSLog(#"Done");
if ([txtGroupName.text length] > 0) {
[self dismissModalViewControllerAnimated:YES];
NSLog(#"Group Name: %#", txtGroupName.text);
NSMutableArray *newDict = [[NSMutableArray alloc] init];
[self.groups setObject:newDict forKey:txtGroupName.text];
NSLog(#"Count:%d", [self.groups count]);
BOOL success = [self.groups writeToFile:self.groupPath atomically:YES];
if(success) {
NSLog(#"Success Saving New Group");
} else {
NSLog(#"Failure Saving New Group");
}
[newDict release];
}
}
Here is what the debug shows:
2010-07-01 00:48:38.586 Contacts[7111:207] Done
2010-07-01 00:48:38.589 Contacts[7111:207] Group Name: C
2010-07-01 00:48:38.590 Contacts[7111:207] Count:3
2010-07-01 00:48:38.592 Contacts[7111:207] Success Saving New Group
However, when I open the .plist file, it still has only 2 groups that I had created manually, and not the new entry.
The files are located in my ~Documents folder.
Any ideas?
How you have initialized groupPath? It should be the path of document directory, not the path of resource directory.
You should do something similar :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME];
You can not edit the file that is present in the workspace.
NSString* plistPath = nil;
NSFileManager* manager = [NSFileManager defaultManager];
if ((plistPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:#"PathTo.plist"]))
{
if ([manager isWritableFileAtPath:plistPath])
{
NSMutableDictionary* infoDict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
[infoDict setObject:#"foo object" forKey:#"fookey"];
[infoDict writeToFile:plistPath atomically:NO];
[manager setAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate] ofItemAtPath:[[NSBundle mainBundle] bundlePath] error:nil];
}
}