Generate a ppt file with byte array/NSData, in objective c? - ios

I have a NSData value, generated from a byte array response. Now I need to save this as a .ppt file in iPhone/iPad, I learned from this link that there is no way to directly do it.
I already tried saving it as a PDF first, but failed in that too, since I'm unable to reproduce the charts from the nsdata.
Now is there another way to get this done other than sending the file through mail associated to the device?
Please do give out only the ways by which I can carry this out in the background without the help of the user? Any help will be appreciated.Thanks

I got it working, tried a lot but nothing worked and finally ran into some random code blocks, using which I got this wonderful piece of code,
//--------------------------------------------------------------------------------generating input URL
NSString *urlAddress = #"url containing the pdf data";
NSURL *theRessourcesURL = [NSURL URLWithString:urlAddress];
//--------------------------------------------------------------------------------defining file location details & writing a ppt file with a name "new.ppt"
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pathFloder = [[NSString alloc] initWithString:[NSString stringWithFormat:#"%#",#"new.ppt"]];
NSString *defaultDBPath = [documentsDirectory stringByAppendingPathComponent:pathFloder];
NSData *tmp = [NSData dataWithContentsOfURL:theRessourcesURL];
[tmp writeToFile:defaultDBPath atomically:YES];

Related

How to upload .xml file in IOS app using Objective-C?

In my IOS app I have one abc.xml file through which I get data and display it on screen (I have already done with that, no issue for doing this), my problem is,on button click I want to upload any .xml file to my app (I have some .xml file in my ipad) and want to replace that .xml file with abc.xml file, (then i will fetch data through that newly uploaded file)
It is just like "choose file" option in web
can we do this in iOS app using Objective-C?
iOS uses .plist setting configuration files. I don't know how well this would work, but you could try something a little like this...
NSMutableDictionary *abcDict = [NSMutableDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"abc" fileType:#"xml"]];
NSString *someString = (NSString*)[abcDict valueForKey:#"someString"];
NSNumber *someNumber = (NSNumber*)[abcDict valueForKey:#"someNumber"];
NSDictionary *someDictionary = (NSDictionary*)[abcDict valueForKey:#"someDict"];
NSArray *someArray = (NSArray*)[abcDict valueForKey:#"someArray"];
BOOL *someBoolean = [((NSNumber*)[abcDict valueForKey:#"someBool"]) booleanValue]
Just change your code depending on your data type. BOOL is a bit weird, but everything else is written just like that. Use the right key names, and if XML doesn't work, try plugging a .plist file into your app!
If i understood what you want, this should make the trick.
NSURL *url = [NSURL URLWithString:linkURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
BOOL success = [db writeToFile:#"locationOfTheFile" atomically:YES];
if (success) {
//all went well
}else{
//error
}
}
edit:
if the file is at the root of your app, you can get the path with this.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
BOOL success = [db writeToFile:[documentsDir stringByAppendingPathComponent:#"fileName"];

This used to work: Displaying image using imageWithContentsOfFile

This was working for me yesterday morning and now it doesn't. So, I suspect something else changed to cause it...but I can't find the change. I've spent hours reverting my code back almost a week and still it's not working (and I know it was working yesterday morning). So, I'm hoping that in posting this specific issue (a symptom?) some ideas will surface that I can evaluate. Thanks.
I download images as they're needed:
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *targetFile = [NSString stringWithFormat:#"%#/%#.%#", documentDirectory, imageName, imageType];
// only download those where an image exists
if(![imageType isEqualToString:#""])
{
// only download the file if there is not already a local copy.
if([filemgr fileExistsAtPath:targetFile] == NO)
{
NSMutableData *imageData = [[NSMutableData alloc] initWithLength:0];
[imageData appendData:data];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *thumbNailFilename = [NSString stringWithFormat:#"%#.%#", imageName, imageType];
NSString *thumbNailAppFile = [documentsDirectory stringByAppendingPathComponent:thumbNailFilename];
}
}
Then display them:
NSString *imageFullName = [NSString stringWithFormat:#"%#%#", [greetingObject valueForKey:#"gid"], [greetingObject valueForKey:#"itp"]];
NSString *fullImagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:imageFullName];
UIImage *greetingImage = [UIImage imageWithContentsOfFile:fullImagePath];
self.greetingImage.image = greetingImage;
The variables "imageFullName" and "fullImagePath" are populated with the correct data and the image files are present on the simulator in the specified directory. Yet, "greetingImage" equals nil.
Here's what I get for "fullImagePath": /Users/Steve2/Library/Application Support/iPhone Simulator/7.1/Applications/8C9F8417-F6E2-4B38-92B3-82A88477CB7F/Documents/165.jpg
Here are the image files:
I have also tried variations using initWithContentsOfFile and dataWithContentsOfFile and get the same result. The greetingImage variable is nil.
I appreciate your ideas. I've even reinstalled Xcode in hopes that something got corrupted. No dice.
Added: One thing I just thought of... I did add the SystemConfiguration.framework to the project yesterday for an unrelated feature. It's currently at the top of the Linked Frameworks and Libraries list. I have no experience working with this. Could it be causing the problem?
Thanks.
Your code looks correct.
I would check that the images themselves are still okay. Looking at the screenshot you posted Finder isn't showing previews of the images which it should do with a valid JPEG. You say that the images are being downloaded so I suspect that they are being corrupted somehow on the way down.
EDIT:
Didn't notice that you were using initWithContentsOfFile. Since you are saving the files as NSData objects you will need to load them into memory as NSData objects and then init a UIImage with the data object, like so:
NSData *imageData = [NSData dataWithContentsOfFile:filePath];
[UIImage imageWithData:imageData];

Need to get an XML from server encoded in windows-1252 for my iOS application

I have an iOS application which is download from server an XML file encoded in Windows 1252.
I am using the following code to save it to my document folder :
NSString *path = #"http://server/file.xml";
NSURL *URL = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSWindowsCP1252StringEncoding]];
NSData *xmlData = [NSData dataWithContentsOfURL:URL];
if(xmlData == nil) {
// Error - handle appropriately
NSLog(#"ERROR");
}
NSString *applicationDocumentsDir=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath=[applicationDocumentsDir stringByAppendingPathComponent:#"annonces.xml"];
[xmlData writeToFile:storePath atomically:TRUE];
NSLog(#"write xml");
It doesn't work, I've got an nil response when I try to read it with the parser. How could I do to get it properly. I cannot change the encoding of te xml which is on the server. If I change the XML encoding manually, I've got a correct response.
This is how I pass the XML string to parse it with XML Dictionnary class :
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *finalPath = [path stringByAppendingPathComponent:#"annonces.xml"];
NSString *string = [[NSString alloc] initWithContentsOfFile:finalPath encoding:NSWindowsCP1252StringEncoding error:NULL];
NSLog(#"string: %#", string);
NSDictionary *items = [NSDictionary dictionaryWithXMLString:string];
NSLog(#"dictionary: %#", items);
Your URL variable contains the url address of the location of the XML file you want to download.
However you are applying NSWindowsCP1252StringEncoding to the url, not to the content of the file.
xmlData is nil because dataWithContentsOfURL: cannot find the file at the location you have specified within URL.
You need to download the file first, then once its downloaded then you can be concerned about what encoding its in and how to parse it.
The way you are using NSWindowsCP1252StringEncoding has got nothing to do with the content of the file.

Read a plist from website

I am incorporating an image gallery into my project. It currently reads from a local plist file, and I need to change it to read from a web server. I've read a number of ways to do this, but can't make it work in my context. This seems maddeningly simple.
Below is my code:
NSString *plistPath =
[[NSBundle mainBundle] pathForResource:#"Images" ofType:#"plist"];
NSArray *imagePaths = [NSArray arrayWithContentsOfFile:plistPath];
You can view my plist here
This is what I've tried to no avail:
//get image URLs
NSURL *plistPath = [NSURL URLWithString:#"http://kpd.altervista.org/Images.plist"];
NSDictionary *imagePaths = [[NSDictionary alloc] initWithContentsOfURL:plistPath];
I'd greatly appreciate anyone's help.
Try this and it should be work :
NSURL *plistPath = [NSURL URLWithString:#"http://kpd.altervista.org/Images.plist"];
NSArray *imagePaths = [NSArray arrayWithContentsOfURL:plistPath];
NSLog(#"%#", imagePaths);
The URL you provide serves a plist that contains an array.
Your code tries to read it as a dictionary.
Just change your code to read it as an array and you'll be one step closer.
But as others have said in the comments, you can't download a file (plist or otherwise) to your bundles directory. You have to download it to your Documents directory or similar.

How to load app with local data and subsequently update it when online.

Right now I have an app that successfully parses JSON from my website. So whenever there is no internet connection, my app crashes. Now I am trying to make it so that when the app is loaded with no internet connection, it will show the data that was shown previously. What would be the best way to do this?
I read this article but I don't know how to embed a JSON file into my app bundle. Could someone explain how to do this?
Thanks in advance!
The best way is:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"YourParsedJSON.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (noInternet){
if ([fileManager fileExistsAtPath: path]){
// if this is true, you have a saved version of your JSON
YourArray = [[NSMutableArray alloc] initWithContentsOfFile: path];
// or
YourDict = [[NSMutableArray alloc] initWithContentsOfFile: path];
}
else{
// first time the app is running, and no internet, no json, inform user about this
}
}
else{
// make an array or dictionary ( what is your JSON )
// response can be a NSDictionary or NSArray
// YourArray = parsedJSON or YourDict = parsedJSON
[YourArray writeToFile:path atomically:YES];
//or
[YourDictionary writeToFile:path atomically:YES];
}
I hope it helps !
Use Apple Reachability sample code to check if your app is able to establish connection to your server.
On first successful request-response, parse the JSON and cache it to disk as a .plist file. This will save you parsing the stored response again. A parsed JSON response can be a NSDictionary or NSArray. Use the writeToFile:atomically: API to write it to disk.
On subsequent request, if reachability fails, i.e. no network connectivity, read the cached response from disk. You need to decide the cache duration and update the plist when a fresh response is fetched.
Hope that helps!
EDIT:
I think I did not understand the question completely. Thanks Xman, for pointing it out. What I would have done in this case is - save the last loaded JSON file to my bundle and use it for displaying information while querying the server and loading updates in the background.
The flow should be like this:
Parse and display data using local JSON file. (Assuming there is local copy of JSON file)
Query the server for latest data.
Upon receiving response, update the bundle with the latest JSON file.
Then, do step 1. In case there is no JSON file, just start from step 2. If there is a Network error display the appropriate information.
This SO question answers how to handle Network connections in iOS: How to check for an active Internet connection on iOS or OSX?
Saving file locally:
Assuming you have the unparsed JSON data in a NSString (responseString) do the following:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, #"latest_json.json"];
NSError *error;
[jsonString_ writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", error)
Reading file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, #"latest_json.json"];
NSString *jsonString_ = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
Previous Answer
Embedding JSON file is similar to embedding any resource into your project. The following method shows you how I added an XML file and accessed it in my app.
Drag and drop your JSON/XML file to your resources group/folder in your XCode window. If you don't have the Resouces folder, it is better you create it. Then in your code do this:
NSString* filePath_ = [[NSBundle mainBundle] pathForResource:#"fileName" ofType:#"json"];
NSString *jsonString = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error: NULL];
the variable jsonstring contails the JSON information. It is upto you how you would like to parse it.

Resources