iOS: read raw plist - ios

I want to read the UserDefaults plist but not as Dictionary or Data. I want it as string like it is when you open it with an editor.
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *homeDir = [documentsPath stringByReplacingOccurrencesOfString:#"Documents" withString:#""];
NSString *defaultsPath = [homeDir stringByAppendingString:[NSString stringWithFormat:#"Library/Preferences/%#.plist", [[NSBundle mainBundle] bundleIdentifier]]];
NSData *data = [NSData dataWithContentsOfFile:defaultsPath];
Already tried:
`NSString *contents = [NSString stringWithContentsOfFile:defaultsPath encoding:NSUTF8StringEncoding error:&error];
which ends up with
The operation couldn’t be completed. (Cocoa error 261.)

Property list formats can be either binary or text. Binary plists can't be loaded into an NSString because strings are for text, not arbitrary binary data. The error you're getting seems to suggest that the file cannot be interpreted as UTF-8, which either means it is encoded using another encoding or is not text at all.
If you are certain that the property list is a text property list, you can use:
NSStringEncoding enc;
NSString *contents = [NSString stringWithContentsOfFile:defaultsPath usedEncoding:&enc error:&error];
This will allow the framework to determine the encoding of the text plist for you. If it isn't a text plist, you can convert it to one using the plutil command line utility:
plutil -convert xml1 file.plist
Or, alternatively you can do this in code by loading the plist using the NSPropertyListSerialization class, obtaining the NSData from it that represents the plist as the XML format, and then convert that to a string.
An example would be [uncompiled and untested]:
// load the file as-is into a data object
NSData *data = [NSData dataWithContentsOfFile:defaultsPath];
// convert the plist data into actual property list structure
id plistFile = [NSPropertyListSerialization propertyListWithData:data
options:0
format:NULL
error:&error];
// get the XML representation of the property list
NSData *asXML = [NSPropertyListSerialization dataWithPropertyList:plistFile
format:NSPropertyListXMLFormat_v1_0
options:0
error:&error];
// convert the NSData object into an NSString object
NSString *asString = [[NSString alloc] initWithData:asXML encoding:NSUTF8StringEncoding];
This should work whether the original plist is in XML or binary format. In this example, I am assuming that the XML representation of the property list is in fact UTF-8 encoded, as this is the most common encoding for XML data.

Related

UI blocking when trying to save data in txt file in iOS

I'm trying to save recieving values in Txt file in delegate method using the below code. Those are Integer values, i'm putting those values in graph meanwhile saving in txt file.
but saving values in txt file is blocking graph plotting.
NSError *error;
NSString *filepath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject] stringByAppendingPathComponent:fileNameString];
NSString *string = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:&error];
NSString *writeString = [NSString stringWithFormat:#"%#\n %#",string,values];
[writeString writeToFile:filepath atomically:YES encoding:NSUTF8StringEncoding error:&error];
PS: I used putting this piece of code dispatch_async, then its not saving all receiving values
If you are pushing on a thread and not all the values are being written, it sounds like a race condition with the thread. Try and do all your string processing on the write thread to make sure that thread is the 'source of truth' and has the most updated information.

Could not able to load Unicode characters from .strings file in cocoa

I am new to Cocoa development. I am using a .strings file to store Key and Value pairs. The value pairs contain some unicode characters like
"\u5f0a\u793e\u306e\u88fd\u54c1\u3092\u8a66\u3057\u3066\u307f\u308b\u3002"
Im using the below statements to parse the strings file
NSString *fname = [[NSBundle mainBundle] pathForResource:#"fileName" ofType:#"strings"];
NSString *fileText = [NSString stringWithContentsOfFile:fname encoding:NSUTF16StringEncoding error:nil];
NSDictionary *dict= [fileText propertyListFromStringsFileFormat];
NSLog(#"%#",[dict valueForKey:#"key"]);
I am getting ouput without '\' like
"u5f0au793eu306eu88fd"
But I want the output with '\' as exactly in the file.
Please help.

dictionaryWithContentsOfFile Returns Nil rather the NSdictionary

I have created a file named Dict.json .Contents of the file are valid json containg
{"mydata":[{
"A":4,
"B":14,
"C":7
},
{
"A":4,
"B":12,
"C":7
},
{
"A":34,
"B":154,
"C":6
},
{
"A":34,
"B":162,
"C":6
}]}
I want to create a NSDictonary from this file .I tried the following but it returns nil .
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Dict" ofType:#"json"];
NSMutableDictionary *newArr1=[NSMutableDictionary dictionaryWithContentsOfFile:filePath];
I am also checking that file is not nil;
NSData *myData = [NSData dataWithContentsOfFile:filePath];
if (myData) {
NSLog("There is Data in File !!!!")
}
For loading the json data you will need NSJSONSerialization to fetch json data from file
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Dict" ofType:#"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *dic1 = [[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil] mutableCopy];
Your code only work on plist file, not on json file.
From the Documentation
+ (id)dictionaryWithContentsOfFile:(NSString *)path
Parameters
path
A full or relative pathname. The file identified by path must contain a string representation of a property list whose root object is a dictionary.
Return Value
A new dictionary that contains the dictionary at path, or nil if there is a file error or if the contents of the file are an invalid representation of a dictionary.
As mentioned above you can only create the dictionary + (id)dictionaryWithContentsOfFile:(NSString *)path using plist file not from the .json.

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.

Encrypted twitter feed

I'm developing an iOS application , that will take a twits from twitter,
I'm using the following API
https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&count=2&screen_name=TareqAlSuwaidan
The problem are feed in Arabic Language ,
i.e the text feed appears like this
\u0623\u0646\u0643 \u0648\u0627\u0647\u0645
How can i get the real text (or how to encode this to get real text) ?
This is not encrypted, it is unicode. The codes 0600 - 06ff is Arabic. NSString handles unicode.
Here is an example:
NSString *string = #"\u0623\u0646\u0643 \u0648\u0627\u0647\u0645";
NSLog(#"string: '%#'", string);
NSLog output:
string: 'أنك واهم'
The only question is exactly what problem are you seeing, are you getting the Arabic text? Are you using NSJSONSerialization to deserialize the JSON? If so there should be no problem.
Here is an example with the question URL (don't use synchronous requests in production code):
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&count=2&screen_name=TareqAlSuwaidan"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSDictionary *object1 = [jsonObject objectAtIndex:0];
NSString *text = [object1 objectForKey:#"text"];
NSLog(#"text: '%#'", text);
NSLog output:
text: '#Naser_Albdya أيدت الثورة السورية منذ بدايتها وارجع لليوتوب واكتب( سوريا السويدان )
Those are Unicode literals. I think all that's needed is to use NSString's stringWithUTF8String: method on the string you have. That should use NSString's native Unicode handling to convert the literals to the actual characters. Example:
NSString *directFromTwitter = [twitterInterface getTweet];
// directFromTwitter contains "\u0623\u0646\u0643 \u0648\u0627\u0647\u0645"
NSString *encodedString = [NSString stringWithUTF8String:[directFromTwitter UTF8String]];
// encodedString contains "أنك واهم", or something like it
The method call inside the conversion call ([directFromTwitter UTF8String]) is to get access to the raw bytes of the string, that are used by stringWithUTF8String. I'm not exactly sure on what those code points come out to, I just relied on Python to do the conversion.

Resources