Play audio from created directory - ios

Hi I'm using the following code to play an audio file
NSString *stringPath = [[NSBundle mainBundle]pathForResource:#"audioFileName" ofType:#"mp3" inDirectory:#"/Downloads"];
NSURL *url = [NSURL fileURLWithPath:stringPath];
NSError *error;
avPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
avPlayer.delegate = self;
[avPlayer play];
But I get an error because my audio files I located in a folder called "Downloads"
Path: AppName/Library/ApplicationSupport/Downloads/audioFileName.mp3
The error I get is that the string stringPath is nil probably because that line of code is written wrong. I know for sure the file is there!
Heres an image using file browsing software
So my question how do i modify the above code to point to my downloads directory when playing a audio file. Thanks
Ive even tried putting the whole path like this.
NSString *stringPath = [[NSBundle mainBundle]pathForResource:#"audioFileName" ofType:#"mp3" inDirectory:#"Library/Application Support/Downloads"];
Status update!
I now do the following and the error is gone but not sure if its pointing to the correct folder still and if so is it possible I don't have permissions to use the files within it. This is a directory i created so is changing permissions to it after its created something I had too do?
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libraryDirectory = [paths objectAtIndex:0];
NSString *stringPath = [[libraryDirectory stringByAppendingPathComponent:#"Downloads"] stringByAppendingPathComponent:#"audioFileName.mp3"];

I believe pathForResource is only for files you include with your app. You have made the audio file in the Library folder which is not in your .app folder... so you could try to use something like:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libraryDirectory = [paths objectAtIndex:0];
NSString *stringPath = [[libraryDirectory stringByAppendingPathComponent:#"Downloads"] stringByAppendingPathComponent:#"audioFileName.mp3"];

Related

path of the directory where ibooks's pdf stored ios

I need to get the already existing pdf files in the device and to upload the selected pdf to the server. I've added one pdf file to iBooks and then tried searching that file in directory using this code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
//NSError *error = nil;
NSArray *filesAtPath = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSLog(#"filesAtpath:%#",filesAtPath);
for (NSString *path in filesAtPath)
{
NSLog(#"add..");
if ([path rangeOfString:#".pdf"].length > 0)
{
//Do whatever you want with the pdf file
NSLog(#"pdf: %#",path);
}
}
but the log shows empty array, could you please tell me, is there any other method to get the pdf list in the device and select one to upload in the server.
No, Apple does not provide access to iBooks library in the same way that it provides some access to the Music library.

Get images from Documents directory to view on UIWebView

i want to get images from my apps Documents directory into the UIwebview in tag.
the Document directory sits in the application root:
/Users/myname/Library/Application Support/iPhone Simulator/7.1-64/Applications/E6B53F7B-CCC0-43A0-B1EB-D7C60E10E6CB/
and the image sits in:
/Users/myname/Library/Application Support/iPhone Simulator/7.1-64/Applications/E6B53F7B-CCC0-43A0-B1EB-D7C60E10E6CB/Documents/image.jpg
my code for the uiwebview is:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#", documentsDirectory];
NSURL *url = [NSURL URLWithString:filePath];
[webView loadHTMLString:HTMLMarkup baseURL:url];
The src attribute is set to just the image name, but that doesn't seem to work. I'm sure its something about the relative path to get to the image, but I don't know where the root of the page loaded on the uiwebview is located.
I thought the code above sets the root path of the uiwebview to the Documents directory so I could call for the image simply by its name.
Does anyone know what the problem is here?
Confusingly, the +URLWithString: method will not work for local files. You need +fileURLWithPath:. This has caught me out a couple of times. Docs here

writing string to txt file in objective c

Pulling my hair out trying to work this out. i want to read and write a list of numbers to a txt file within my project. however [string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error] doesnt appear to write anything to the file. I can see there is the path string returns a file path so it seems to have found it, but just doesnt appear to write anything to the file.
+(void)WriteProductIdToWishList:(NSNumber*)productId {
for (NSString* s in [self GetProductsFromWishList]) {
if([s isEqualToString:[productId stringValue]]) {
//exists already
return;
}
}
NSString *string = [NSString stringWithFormat:#"%#:",productId]; // your string
NSString *path = [[NSBundle mainBundle] pathForResource:#"WishList" ofType:#"txt"];
NSError *error = nil;
[string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", error.localizedFailureReason);
// path to your .txt file
// Open output file in append mode:
}
EDIT: path shows as /var/mobile/Applications/CFC1ECEC-2A3D-457D-8BDF-639B79B13429/newAR.app/WishList.txt so does exist. But reading it back with:
NSString *path = [[NSBundle mainBundle] pathForResource:#"WishList" ofType:#"txt"];
returns nothing but an empty string.
You're trying to write to a location that is inside your application bundle, which cannot be modified as the bundle is read-only. You need to find a location (in your application's sandbox) that is writeable, and then you'll get the behavior you expect when you call string:WriteToFile:.
Often an application will read a resource from the bundle the first time it's run, copy said file to a suitable location (try the documents folder or temporary folder), and then proceed to modify the file.
So, for example, something along these lines:
// Path for original file in bundle..
NSString *originalPath = [[NSBundle mainBundle] pathForResource:#"WishList" ofType:#"txt"];
NSURL *originalURL = [NSURL URLWithString:originalPath];
// Destination for file that is writeable
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSURL *documentsURL = [NSURL URLWithString:documentsDirectory];
NSString *fileNameComponent = [[originalPath pathComponents] lastObject];
NSURL *destinationURL = [documentsURL URLByAppendingPathComponent:fileNameComponent];
// Copy file to new location
NSError *anError;
[[NSFileManager defaultManager] copyItemAtURL:originalURL
toURL:destinationURL
error:&anError];
// Now you can write to the file....
NSString *string = [NSString stringWithFormat:#"%#:", yourString];
NSError *writeError = nil;
[string writeToFile:destinationURL atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", writeError.localizedFailureReason);
Moving forward (assuming you want to continue to modify the file over time), you'll need to evaluate if the file already exists in the user's document folder, making sure to only copy the file from the bundle when required (otherwise you'll overwrite your modified file with the original bundle copy every time).
To escape from all the hassle with writing to a file in a specific directory, use the NSUserDefaults class to store/retrieve a key-value pair. That way you'd still have hair when you're 64.

NSURL is always nil dispite encoding

I'm generating a PDF file and am attempting to preview it as shown below, but URL routinely returns NIL despite my formatting (which is what seems to resolve everyone else's issue with this common problem). I must be missing something more. Any ideas?
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [path objectAtIndex:0];
docDirectory = [docDirectory stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *URL = [[NSBundle mainBundle] URLForResource:docDirectory withExtension:#"pdf"];
if (URL) {
// Initialize Document Interaction Controller
self->documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:URL];
// Configure Document Interaction Controller
[self->documentInteractionController setDelegate:self];
// Preview PDF
[self->documentInteractionController presentPreviewAnimated:YES];
}
Your path creation seems all out of whack. Try something like this:
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [path objectAtIndex:0];
NSString *filename = #"myfile.pdf"; // replace with the actual filename you used
NSString *fullPath = [docDirectory stringByAppendingPathComponent:filename];
NSURL *fullURL = [NSURL fileURLWithPath:fullPath];
In the code you posted you don't provide a filename. You have the Documents directory and the pdf extension. And there is no need to "percent escape" the URL in this case.
You are probably confused of how to obtain the path to your file: NSSearchPathForDirectoriesInDomains is used to get an absolute path to (for example) your documents directory. NSBundle's URLForResource:withExtension: on the other hand searches the app wrapper for a file with the provided name.
Mixing the two would do no good. You should probably just look into the documents directory.

How to download dataset for Vuforia app?

I'm developing sample apps from Vuforia SDK 1.5.9 in Xcode 4.2 with iOS 5.1. In that version I could not make my trackable datasets on my own - I have to use online solution from Qualcomm. Does anyone know or have anyone tried to download datasets from remote location? So you generate them as usual but download them into app from server, so I can for example choose which one to download and use on fly?
Yesterday I've given it a quick try with this:
-(void)setupMarkers{
NSString *filePathX;
//connect to the remot location
NSURL *urlD = [NSURL URLWithString:[NSString stringWithFormat:#"%#/frames.dat",kURLServer]];
NSData *urlData = [NSData dataWithContentsOfURL:urlD];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"frames.dat"];
[urlData writeToFile:filePath atomically:YES];
}
NSURL *urlX = [NSURL URLWithString:[NSString stringWithFormat:#"%#/frames.xml",kURLServer]];
NSData *urlDataX = [NSData dataWithContentsOfURL:urlX];
if ( urlDataX )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"frames.xml"];
[urlDataX writeToFile:filePath atomically:YES];
filePathX = filePath;
}
//put them into markersArray
[self.markersArray addObject:filePathX];
}
I know it is ugly, but as I said it was a quick try, but it didn't work at all. I know there is new Vuforia SDK 2.0 with clouds and stuff, but afaik I would have to use iOS6 & Xcode 4.5 - which is not a solution for me right now.
Actually my "quick try" wasn't that bad after all :)
Here's what i did:
wrote a method -(void)setupMarkers in which I dwonload .dat and .xml files (like in question)
in QCARUtils.mm I changed in - (QCAR::DataSet *)loadDataSet:(NSString *)dataSetPath one line:
// Load the data set from the App Bundle
// If the DataSet were in the Documents folder we'd use STORAGE_ABSOLUTE and the full path
if (!theDataSet->load([dataSetPath cStringUsingEncoding:NSASCIIStringEncoding], QCAR::DataSet::STORAGE_ABSOLUTE))//STORAGE_APPRESOURCE)){
...
}
works like a charm :)
p.s. I'll wait a while so if anyone will come up with better answer ;)

Resources