How can I see components of NSData? - pdf

I am trying to write a PDF file from NSData I got from an http request and then display the pdf. When I call [response description], I get <30>, so I am at least getting something back. However, when I run this code, an error comes up: "failed to find PDF header: `%PDF' not found."
Is there some way to see what my NSData is if it is not a pdf? Am I going about this incorrectly? Thanks!
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if (response) {
NSString *description = [response description];
NSLog(#"description: %#", description); //this prints: <30>
} else {
NSLog(#"response is nil");
}
NSArray *dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *filename = #"Test1.pdf";
NSString *dirPath = [dirs objectAtIndex:0];
NSError *error = nil;
NSString *path=[dirPath stringByAppendingPathComponent:filename];
[response writeToFile:path atomically:YES];
NSLog(#"Write returned error: %#", [error localizedDescription]);
NSURL *pdfUrl = [NSURL fileURLWithPath: path];
[webView loadRequest:[NSURLRequest requestWithURL:pdfUrl]];

Related

App crash with " Thread 90: EXC_BAD_ACCESS (code=1, address=0x18)" in Objective C

-(void)writeAllCategoriesInJson:(NSDictionary *)dict
{
NSArray *arry_allCategory = [[NSArray alloc] initWithObjects:dict, nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arry_allCategory options:NSJSONWritingPrettyPrinted error:&error];
if (!jsonData && error){
NSLog(#"Error creating JSON: %#", [error localizedDescription]);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// Build the path, and create if needed.
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"Categories.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}
// The main act...
[[jsonString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}
Here app crash with
"Thread 90: EXC_BAD_ACCESS (code=1, address=0x18)"
on below line:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arry_allCategory options:NSJSONWritingPrettyPrinted error:&error];
What is the issue on this line. Its working fine all time and in between its crashed. I try my best but the issue is still occuring.

Using apples suggested code isnt excluding files from icloud backup

I have an app that has been rejected 3 times due to icloud backup issues. Apple have written back to say that I need to use there bit of code to exclude the files from being backed up. However this isnt working and i am at wits end.
Here is the code i've used
- (BOOL)downloadFile:(NSString *)fileURI targetFolder:(NSString *)targetFolder targetFilename:(NSString *) targetFilename{
#try{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:fileURI];
if(![url setResourceValue:#"YES" forKey:NSURLIsExcludedFromBackupKey error:&error]){
NSLog(#"KCDM: Error excluding %# from backup %#", fileURI, error);
}else{
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingString:targetFolder];
NSError *error = nil;
if(![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&error];
}
NSString *filePath = [NSString stringWithFormat:#"%#/%#%#", documentsDirectory,targetFolder,targetFilename];
return [urlData writeToFile:filePath atomically:YES];
}
}
}
#catch(NSException * e){
NSLog(#"Error download: %#",e);
}
return false;
}
what am i doing wrong?
You try to set NSURLIsExcludedFromBackupKey for the http://-Url you download from the web. That won't work.
You have to set this key-value pair for the actual file that is saved on the device.
Additionally you are not supposed to set this value to the string #"YES", you must use a NSNumber object representing the boolean value YES.
For example:
NSString *filePath = [NSString stringWithFormat:#"%#/%#%#", documentsDirectory,targetFolder,targetFilename];
if ([urlData writeToFile:filePath atomically:YES]) {
// did write correctly
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
if(![fileURL setResourceValue:#YES forKey:NSURLIsExcludedFromBackupKey error:&error]){
NSLog(#"KCDM: Error excluding %# from backup %#", fileURI, error);
return NO;
}
// could set NSURLIsExcludedFromBackupKey
return YES;
}
// could not write to file
return NO;

checking for bad NSURLConnection

i am new to Objective-C and going through the book, The Big Nerd Ranch Guide to Objective-C programming..
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSURL *url = [NSURL URLWithString:#"http://www.google.com/imagess/logos/ps_logo2.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSError *error =nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:NULL
error:&error];
if(!data){
NSLog(#"fetch failed %#", [error localizedDescription]);
return 1;
}
NSLog(#"the files is %lu bytes", [data length]);
BOOL written = [data writeToFile:#"/tmp/google.png"
options:NSDataWritingAtomic
error:&error];
if(!written){
NSLog(#"write failed: %#",[error localizedDescription]);
return 1;
}
NSLog(#"Success!");
NSData *readData = [NSData dataWithContentsOfFile:#"/tmp/google.png"];
NSLog(#"the file read from disk has %lu bytes", [readData length]);
}
return 0;
}
the problem is this, if i change the *url to http://aFakeDomain.com/imimimi/myImage.png then my data object will be nill because there is no HOST and everything works fine.. but if i use google as the domain and point to a bad file location then the data object stil has header info and is NOT nil thus i never get the error i should.
whats the best way to make sure that the *url successfully found a file.
thanks
You will need to pass a response to the NSURLConnection call and then check its status code:
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&httpResponse
error:&error];
int code = [httpResponse statusCode];
you will get a 404 status code in your case.
NSUrlResponce *responce = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&responce
error:&error];
if (error) {
// handle the error
}
if (![[responce MIMEType] isEqualToString:#"image/png"]) {
// failed to get png file
}
There are also some mistakes of the file name;
instead of #"/tmp/google.png", you should use the code list blow:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"google.png"];

NSApplicationSupportDirectory invalid CFStringRef

I'm trying to store a file in the NSApplicationSupportDirectory, since i have a preloaded folder in my app, which i want to add files to once the app have been initialized. I'm trying to NSLog the content of the file, so i can see if it actually worked. From the debugger, i can see that the content is , which i don't not what means. Anybody?
NSString *document = [NSString stringWithFormat:#"%# %# %# %# %#", description, focus, level, equipment, waterDepth];
//NSLog(#"%#", document);
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *supportDirectory = [paths objectAtIndex:0];
//filename
NSString *filename = [NSString stringWithFormat:#"%#/%#", supportDirectory,[_nameTextField.text stringByAppendingString:#".txt"]];
NSLog(#"%#", supportDirectory);
NSLog(#"%#", filename);
[document writeToFile:filename atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
NSString *content = [[NSString alloc]initWithContentsOfFile:filename usedEncoding:nil error:nil];
NSLog(#"%#", content);
You're not passing a string encoding, you are passing NSStringEncodingConversionAllowLossy which is an option that can affect how encoding conversion happens for certain methods (not the one you're using). You need to pass something like NSUTF8StringEncoding.
When you write or read files, it is highly recommended to use the error parameter and handle the cases where you get an error. Also, this is very useful to help you debug your code.
For example, in your case, you can do like this:
NSError *error = nil;
BOOL success = [document writeToFile:filename atomically:NO encoding:NSStringEncodingConversionAllowLossy error:&error];
if (!success) {
NSLog(#"Could not write file: %#", error);
} else {
NSString *content = [[NSString alloc]initWithContentsOfFile:filename usedEncoding:nil error:&error];
if (!content) {
NSLog(#"Could not read file: %#", error);
}
}
If you get an error that says that The operation couldn’t be completed. No such file or directory, that means that you did not previously create the folder. So you create it before trying to add content to it:
NSString *supportDirectory = [paths objectAtIndex:0];
NSError *error = nil;
BOOL success;
if (![[NSFileManager defaultManager] fileExistsAtPath: supportDirectory]) {
success = [[NSFileManager defaultManager] createDirectoryAtPath:supportDirectory withIntermediateDirectories:YES attributes:nil error:&error];
if (!success) {
NSLog(#"Could not create directory: %#", error);
}
}

Getting the contents of a file in Xcode

In my project I have a plain text file called GAME.js, and I'm trying to get the contents of the file.
[NSString stringWithContentsOfFile:#"GAME.js" encoding:NSUTF8StringEncoding error:nil];
sounds like it should work, but it's just returning an empty string.
Please help me fix this.
Put GAME.js into the Resources folder in your Xcode project and use the following code to get the contents of the file.
NSError *error = nil;
NSString* path = [[NSBundle mainBundle] pathForResource:#"GAME" ofType:#"js"];
NSString* gameFileContents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
If you pass in a NSError it will tell you exactly what the problem is:
NSError *error = nil;
NSString *myString = [NSString stringWithContentsOfFile:#"GAME.js" encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
} else {
NSLog(#"%#", myString);
}
NSError Documentation
Also, check to see if it is in your documents directory which can be accessed with NSSearchPathForDirectoriesInDomains:
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fullPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"GAME.js"];
NSString *myString = [NSString stringWithContentsOfFile:fullPath encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"%# - %#", [error localizedDescription], [error localizedFailureReason]);
} else {
NSLog(#"%#", myString);
}