Can't convert app bundle to NSData - iphone

I'm trying to convert my bundle to NSData so that I can hash the data and have a server verify the hash before allowing downloads. The only problem is that when I try to convert the bundle to NSData, I get Error: The operation couldn’t be completed. (Cocoa error 257.) I looked up error 257 and it means that the bundle couldn't be read due to a permissions problem. What am I doing incorrectly? Thanks for your help.
NSString *bundlePath = [[NSBundle mainBundle] resourcePath];
NSLog(#"%#", bundlePath);
NSError *error;
NSData *bData = [NSData dataWithContentsOfFile:bundlePath options:nil error:&error];
NSLog(#"Error: %#", [error localizedDescription]);

If piracy protection is your ultimate goal, refer to this for a little insight and code.
http://thwart-ipa-cracks.blogspot.com/2008/11/detection.html?m=1

Related

Parsing Local XML File Works, Downloaded XML File Doesn't

I have this problem when I fetch an XML file from the internet and then parse it, where I get this error:
Error while parsing the document: Error Domain=SMXMLDocumentErrorDomain Code=1 "Malformed XML document. Error at line 1:1." UserInfo=0x886e880 {LineNumber=1, ColumnNumber=1, NSLocalizedDescription=Malformed XML document. Error at line 1:1., NSUnderlyingError=0x886e7c0 "The operation couldn’t be completed. (NSXMLParserErrorDomain error 5.)"}
Here is an extract from the code (I believe I am only showing the most relevant code, if you need more, please ask.)
// Create a URL Request and set the URL
NSURL *url = [NSURL URLWithString:#"http://***.xml"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Display the network activity indicator
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
// Perform the request on a new thread so we don't block the UI
dispatch_queue_t downloadQueue = dispatch_queue_create("Download queue", NULL);
dispatch_async(downloadQueue, ^{
NSError* err = nil;
NSHTTPURLResponse* rsp = nil;
// Perform the request synchronously on this thread
NSData *rspData = [NSURLConnection sendSynchronousRequest:request returningResponse:&rsp error:&err];
// Once a response is received, handle it on the main thread in case we do any UI updates
dispatch_async(dispatch_get_main_queue(), ^{
// Hide the network activity indicator
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
if (rspData == nil || (err != nil && [err code] != noErr)) {
// If there was a no data received, or an error...
NSLog(#"No data received.");
} else {
// Cache the file in the cache directory
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString* path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"init.xml"];
//NSLog(#"%#",path);
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
[data writeToFile:path atomically:YES];
//NSString *sampleXML = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"xml"];
NSData *data = [NSData dataWithContentsOfFile:path];
// create a new SMXMLDocument with the contents of sample.xml
NSError *error;
SMXMLDocument *document = [SMXMLDocument documentWithData:data error:&error];
// check for errors
if (error) {
NSLog(#"Error while parsing the document: %#", error);
// return;
}
Firstly, I have connected the iPhone to an XML feed which it has fetched and written to the path of the variable path. Then I check for errors in the XML document and I get that error every time.
However, if I use a local XML file which I have placed in the main folder of my application there is no problem fetching all the data.
Using the code:
NSString *sampleXML = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"xml"];
So does anyone have an idea as to what I can have done wrong? It seems as if it doesn't download and store the XML file to the iPhone's cache, however NSLog(); seems to show it differently. Obviously the local file is the same as the file on the internet.
Furthermore, I already tried to save the file to the path without any results, though.
A couple of observations:
The key issue would appear to be that you retrieved the data in rspData, but when you write it to your temporary file, you're writing data, not rspData. So change the line that says:
[data writeToFile:path atomically:YES];
to
[rspData writeToFile:path atomically:YES];
Frankly, I don't even see the data variable defined at that point (do you have some ivar lingering about?). I'd be ruthless about getting rid of any ivars or other variables that you don't need, so that you don't accidentally refer to some unused variable. Anyway, just use the rspData that you retrieved rather than some other variable.
Why are you even writing that to a file, only to then read the file into another NSData that you pass to your XML parser? That seems entirely unnecessary. Just go ahead and use the rspData you initially retrieved. If you want to save the NSData to a file so you can examine it later for debugging purposes, that's fine. But there's no point in re-retrieving the NSData from the file, as you already have it in a rspData already.
If you encounter these errors in the future, feel free to examine the contents of the NSData variable with a debugging line of code, something like:
NSLog(#"rspData = %#", [[NSString alloc] initWithData:rspData encoding:NSUTF8StringEncoding]);
When you do that, you can look at the string rendition of the NSData, and usually the problem will become self evident.
As a complete aside, in your debugging error handler, you have a line that says:
NSLog(#"No data received.");
I might suggest you always include any errors that might be provided, e.g.:
NSLog(#"No data received: error = %#", err);
iOS provides useful error messages, so you should avail yourself of those.

ios not finding a txt file using stringWithContentsOfFile

I have a text file thetext.txt. Which is in my project and is copied on build, in build settings. In the same way that my GL shaders and textures are (which work fine.)
NSError *errorReading;
NSArray *linesOfText = [[NSString stringWithContentsOfFile:#"thetext.txt"
encoding:NSUTF8StringEncoding
error:&errorReading]
componentsSeparatedByString:#"\n"];
NSLog(#"Reading error %#",errorReading);
It prints the following to console.
Reading error Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x896fff0 {NSFilePath=thetext.txt, NSUnderlyingError=0x896ff60 "The operation couldn’t be completed. No such file or directory"}
Have I missing something?
This fails because you are passing the file name and not the path to the file. Try something like this
NSString* filePath = [[NSBundle mainBundle] pathForResource:#"thetext" ofType:#"txt"];
NSError *errorReading;
NSArray *linesOfText = [[NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:&errorReading]
componentsSeparatedByString:#"\n"];
NSLog(#"Reading error %#",errorReading);
Hopefully there will be no error!

The operation couldn’t be completed. (Cocoa error 260.)

I'm new on IOS development and i'm working on a pdf application and i need to store a PDF file on a NSData variable, I have the PDF path but i get this message error when i try to put this pdf on the NSData variable using dataWithContentsOfFile her is my simple code :
NSError *error;
NSString *PdfPath = [NSString stringWithFormat:(#"%#"),document.fileURL ];
NSString *newPath = [PdfPath stringByReplacingOccurrencesOfString:#"file://localhost" withString:#""];
NSLog(#"OriginalPdfPath => %#", newPath);
NSData *pdfData = [NSData dataWithContentsOfFile:newPath options:NSDataReadingUncached error:&error];
NB : the pdf path is in this format : /Users/bluesettle/Library/Application%20Support/iPhone%20Simulator/6.0/Applications/BBEF320E-7E2A-49DA-9FCF-9CFB01CC0402/ContractApp.app/Pro.iOS.Table.Views.pdf
thanks for your help
Cocoa error 260 is a NSFileReadNoSuchFileError (as listed in FoundationErrors.h), meaning the file could not be found at the path you specified.
The problem is that your path still contains encoded spaces (%20), because you're basing it on the URL. You can simply do this:
NSData *pdfData = [NSData dataWithContentsOfFile:[document.fileURL path]];
Try to use NSBundle
NSString *newPath = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"pdf"]
Edit:
Than you can use bundleWithPath method, here is an example:
NSString *documentsDir= [NSString stringWithFormat:#"%#/Documents", NSHomeDirectory()];
NSString *newPath= [[NSBundle bundleWithPath:documentsDir] bundlePath];

What is real issue with the NSData in my code

I want to send json service when the user search text on searchbar. Here the issue is that I return null value of NSData object, what the issue is here? If I define the same url which I print in console that works but what's the issue here?
-(void)doIt{
NSURL *url = [NSURL URLWithString:weburls];
NSData *data =[NSData dataWithContentsOfURL:url];
[self getData:data];
}
If I will write like that then it works, but I want to call the service on the searchbar event but there is a problem
NSString *weburl = [NSString stringWithFormat:#"%#%#",
#"http://192.168.1.196/ravi/iphonephp?mname=",searchText];
NSLog(#"%#",weburl);
NSURL *url = [NSURL URLWithString:weburl];
NSLog(#"the url is : %#",url);
NSError *error;
NSData *data =[NSData dataWithContentsOfURL:url options:nil error:&error];
NSLog(#"Data is :%#",data);
NSLog(#"the Error massage is : %#",error);
[self getData:data];
Gives me console value like
customCellDemo[1553:f803] the url is : http://192.168.1.196/ravi/iphonephp?mname=a
2012-03-16 15:26:36.259 customCellDemo[1553:f803] Data is :(null)
2012-03-16 15:26:43.624 customCellDemo[1553:f803] the Error massage is : Error
Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)"
UserInfo=0x6ab2760 {NSURL=http://192.168.1.196/ravi/iphonephp?mname=a}
From the manual of dataWithContentsOfURL;
Return Value: A data object containing the data from the location
specified by aURL. Returns nil if the data object could not be
created.
In other words, it can either not create an NSData (unlikely) or it can probably not get any data from your supplied URL. I suggest you try to use dataWithContentsOfURL:options:error: instead to get an error code and be able to diagnose the problem.

Getting NSData length zero? Error: Cocoa error 60

NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:currentVideoDownload];
filePath = [filePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[responseData writeToFile:filePath atomically:YES];
NSError *error;
NSData *mediaData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMapped error:&error];
NSLog(#"Length:%d Error:%#",[mediaData length],[error localizedDescription]);
LOG value: Length:0 Error: The operation could not be completed.
(Cocoa error 60)
Data is saving on file path properly but while fetching data from same path getting zero.
Thanks in advance.
The issue is that you are not writing to a writable file path. This is most likely because you are escaping the file path, which is not necessary, and in fact could cause IO reads/writes to fail if the escaped path does not exist. Percent escapes should only be used for HTTP requests, or related NSURL operations. Try removing the line:
filePath = [filePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];