I did this many times before but now it fails.
I want to access a file shipped within my app.
NSString* path = [[NSBundle mainBundle] pathForResource:#"information" ofType:#"xml"];
returns
/Users/eldude/Library/Application Support/iPhone Simulator/7.0.3/Applications/5969FF96-7023-4859-90C0-D4D03D25998D/App.app/information.xml
which is correct - checked in terminal and all that. However, trying to parse the path fails
NSURL* fileURL = [NSURL URLWithString:path];
NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithContentsOfURL:fileURL];
[nsXmlParser setDelegate:self];
if(![nsXmlParser parse]){
NSError* e = nsXmlParser.parserError;
NSLog(#"ERROR parsing XML file: \n %#",e);
self = NULL;
}
with
Error Domain=NSCocoaErrorDomain Code=-1 "The operation couldn’t be completed. (Cocoa error -1.)" UserInfo=0xb9256f0 {NSXMLParserErrorMessage=Could not open data stream}
Ideas anyone?
File URLs and network URLs are different.
From the Apple documentation:
Important: To create NSURL objects for file system paths, use
fileURLWithPath:isDirectory:
or just
fileURLWithPath:
Example:
NSString *filePath = #"path/file.txt";
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSLog(#"fileURL: %#", [fileURL absoluteURL]);
NSURL *netURL = [NSURL URLWithString:filePath];
NSLog(#"netURL: %#", [netURL absoluteURL]);
NSLog Output:
fileURL: file:///path/file.txt
netURL: path/file.txt
Related
I am trying to figure out way to create MSStickers with images that are hosted on the web. I can create MSStickers with local images, e.g.:
NSString *imagePath = [[NSBundle mainBundle] pathForResource: #"image_name"
ofType: #"png"];
NSURL *imageURL = [NSURL fileURLWithPath: urlString];
MSSticker *sticker = [[MSSticker alloc] initWithContentsOfFileURL: stickerURL
localizedDescription: #"my-sticker"
error: &err];
But I cannot do something like this:
NSString *imageURLString = #"https://my-cdn/my-sticker.png";
NSURL *imageURL = [NSURL urlWithString: urlString];
MSSticker *sticker = [[MSSticker alloc] initWithContentsOfFileURL: stickerURL
localizedDescription: #"my-sticker"
error: &err];
No, it's not possible for the moment.
But you can do this, which is not that far from what you want:
Download the picture from your server
Store it on local directory of the device
Use the URL of this local file to create your sticker
Optional : If you don't need the image anymore, erase it from the directory
I have this code here:
NSString *stringURL = #"\\\\SERVER\\FOLDER\\FOLDER\\FTP\\ANC\\ANC.pdf";
NSURL *url = [NSURL fileURLWithPath:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
but urlData returned nill
I have tried datawithcontentsoffile but I got a warning when using the url variable with it.
When I goto this url file://SERVER/FOLDER/FOLDER/FTP/ANC.pdf in Windows, it opens the file, but on mac it does not not.
I have also tried the following:
NSString *stringURL = #"file://SERVER/FOLDER/FOLDER/FTP/ANC.pdf";
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:stringURL]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
// handle response
}] resume];
// NSURL *url = [NSURL URLWithString:stringURL];
// NSData *urlData = [NSData dataWithContentsOfURL:url];
but get these errors:
NSErrorFallingURLStringKey
NSErrorFallingURLKey
NSLocalizedDescription
NSUnderlyingError
UPDATE I am able to get url not return nill with the following:
NSURL *url = [NSURL fileURLWithPath:#"file:///server/FOLDER/FOLDER/FTP/ANC/ANC.pdf"];
however, this returns nill:
NSData *urlData = [NSData dataWithContentsOfURL:url];
I added the error: to dataWithContentsofURL
and it returned this:
connectionError NSError * domain: #"NSCocoaErrorDomain" - code: 260 0x166d8af0
I looked at the file in question via Get Info and it starts out like this smb://server/folder/folder/ANC/ANC.pdf
NSData and URLs: There be dragons
+[NSData dataWithContentsOfURL:] can return nil for any number of reasons. If anything goes wrong when attempting to use that URL this method will return nil. For example the file may not exist, the network connection may time out, or the URL may even be malformed. nil is returned and the application has no idea why.
+ [NSData dataWithContentsOfURL:options:error:] on the other hand, will tell the caller what went wrong. When nil is returned the error argument will be populated with an object that describes the problem that occured. Using this method would directly answer the question of "why".
Both of these are synchronous methods and their use for working with files, network resources, and especially files served from a network resource is discouraged. These methods will block the caller and are not really intended for these kinds of uses. It's better to use an input stream or NSURLSession instead.
SMB Not Supported
From your question though it seems you are trying to access a file that exists on an SMB share. Unforunately iOS does not support SMB - even if you had a correctly formatted smb URL (i.e. smb://servername/sharename/filename.pdf) you would be unable to access it without using a third party SMB implementation.
Using FTP in place of SMB, however, should work.
Just need to do some minor change, Actually your pdf file is on server so you have to change your code like this.
NSURL *url = [NSURL URLWithString:stringURL];
I tried this and its working fine.
If your file is in application's main bundle than you can use fileURLWithPath.
If you have a valid windows file path with backslash separators, there is a CoreFoundation method to convert it to a CFURL/NSURL object
NSString *stringURL = #"\\\\SERVER\\FOLDER\\FOLDER\\FTP\\ANC\\ANC.pdf";
NSURL *url = (NSURL *)CFBridgingRelease(CFURLCreateWithFileSystemPath(kCFAllocatorDefault, stringURL, kCFURLWindowsPathStyle, false));
If the string starts with file:// it's a Mac URL string with the file scheme and you can use
NSString *fileURLString = #"file:///Applications";
NSURL *url = [NSURL URLWithString:fileURLString];
Consider that a valid file scheme string must have a third slash for the root folder after the two slashes for the scheme.
The method fileURLWithPath can only be used if the string starts with a single slash, it adds the file:// scheme implicitly.
NSString *pathString = "/Applications";
NSURL *url = [NSURL fileURLWithPath: pathString];
Make sure URL contains http:// OR https://.
For example: http://SERVER/FOLDER/FILE.pdf
Two things to keep in mind while accessing a file in iOS application:
If you are accessing a file from iOS application sandbox(document or cache directory) then use this:
NSURL *url = [NSURL fileURLWithPath:strUrl];
If you are accessing a file from any server in iOS application then use this:
NSURL *url = [NSURL URLWithString:strUrl];
NOTE: You cannot access a file from your mac in iOS application when running from simulator.
Hope this helps!
please check your code with this code
-(void)downloadPdfBtnPressed:(id)sender
{
NSString *dowloadURL = [DownloadUrlArray objectAtIndex:[sender tag ]];
NSString *filename =[dowloadURL lastPathComponent];
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"/Download"];
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:nil];
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:dowloadURL]];
if(pdfData)
{
stringPath = [stringPath stringByAppendingPathComponent:filename];
[pdfData writeToFile:stringPath atomically:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[singletonObj getTranslationForKey:#"AlereTitleContactus"]
message:#"PDF file is downloaded"
delegate:nil
cancelButtonTitle:[singletonObj getTranslationForKey:#"alertOK"]
otherButtonTitles:nil];
[alert show];
}
}
I am preparing the URL for one method of AVURLAsset:
+ (AVURLAsset *)URLAssetWithURL:(NSURL *)URL options:(NSDictionary *)options
My URL belongs to a file which is written to the document path of my app. The result of NSLog the path is:
/var/mobile/Containers/Data/Application/E0E64E72-9A47-4E62-B9C6-818AB8BF3F4C/Documents/audio.wav
After got the NSString *path, I tried to convert NSString to NSURL by [NSURL URLWithString:path] and [NSURL fileURLWithPath:path], but both of them are incorrect for URLAssetWithURL.
Error of URLWithString is:
Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could
not be completed" UserInfo=0x170269f80 {NSUnderlyingError=0x17405f440
"The operation couldn’t be completed. (OSStatus error -12780.)",
NSLocalizedFailureReason=An unknown error occurred (-12780),
NSLocalizedDescription=The operation could not be completed}
And fileURLWithPath crashed the app.
I know url = [[NSBundle mainBundle] URLForResource:fileURL withExtension:#"wav"] will fit the situation. But I want to get the url of a local file to fit URLAssetWithURL as well. Any idea? Thanks.
This way of getting a file from the documents should work:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths.firstObject stringByAppendingPathComponent:#"file"] stringByAppendingPathExtension:#"wav"];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSURL *url = [NSURL fileURLWithPath:path];
}
I am trying to play an MP3 file, however I am having problems with my code. This is what I have:
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
if (!audioPlayer) {
NSLog(#"localizedDescription : %#", [error localizedDescription]);
} else {
[audioPlayer play];
}
and this is the error I am reciving
localizedDescription : The operation couldn’t be completed. (OSStatus error -43.)
How do I stop this from happening? I want to play my sound once then stop it, but it can't even start.
The issue is probably caused by the path being invalid.
Try building it as follows
NSString *soundPath =[[NSBundle mainBundle] pathForResource:#"audiofile" ofType:#"mp3"];
NSURL *soundURL = [NSURL URLWithString:soundPath];
instead.
Also make sure that audiofile.mp3 is included in the current target.
My app downloads a pdf and then on a button press brings it up in a new view.
I get the error:
-[NSURL initFileURLWithPath:]: nil string parameter'
After some troubleshooting I pinned the problem to somewhere in this code snippet. The path that is being pointed to is in the /Documents folder where the downloaded pdf is placed. Thus the document is not in the main bundle.
NSString *path = [[NSBundle mainBundle] pathForResource:PDFpathwithextension ofType:#"pdf"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
Here's the download code:
//Start an NSURL connection to download from the remotepath
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:remotepathURL];
//Store the Data locally as PDF File
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:[newdata.ThirdPickerName stringByAppendingFormat:#".pdf"]];
pdfData writeToFile:filePath atomically:YES];
As NSURL is telling you, you've handed it nil instead of a valid path.
nil here means no such resource could be found by that name. Indeed, your question suggests you're well aware of this.
Since you claim your app already downloads a PDF, does it actually write that out to disk? If so, you should know where the resulting file is from doing that. If not, you first need to write the actual download code!