I found a code snippet here, which I wanted to use, but I can't figure out how to make it back "to string" and see if it works...
// some strings for test
NSString *cpu = [[NSString alloc] initWithFormat:#"%.0f", [_cpuSlider value]];
NSString *ram = [[NSString alloc] initWithFormat:#"%.0f", [_ramSlider value]];
NSString *hdd = [[NSString alloc] initWithFormat:#"%.0f", [_hddSlider value]];
// put them into dictionary
NSDictionary *test = [NSDictionary dictionaryWithObjectsAndKeys:cpu, #"CPU", ram, #"RAM", hdd, #"HDD", nil];
// start of the code from page above
NSMutableData *myData = [[NSMutableData alloc]init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:myData];
[archiver encodeObject:test forKey:#"MyKEY"];
[archiver finishEncoding];
id testJson = [NSJSONSerialization JSONObjectWithData:myData options:0 error:nil];
// end of code
// HERE I'd like know what to put in to see it as a string..e.g. { "CPU"=value; etc...}
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"MLIA" message:????? delegate:nil cancelButtonTitle:#"Zavřít" otherButtonTitles: nil];
[av show];
Thanks a lot!
NSKeyedArchiver doesn't produce JSON (AFAIK), so I don't know how that linked example could possibly work. If you want to JSON-encode a dictionary, you would use +dataWithJSONObject:options:error::
NSError *err;
NSData *json = [NSJSONSerialization dataWithJSONObject:test options:0 error:&err];
NSAssert1(json, #"Error: %#", err);
// If not using ARC, remember to (auto)release repr.
NSString *repr = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
[[UIAlertView …] … message:repr …];
Related
This is for my iOS app using Core Data.
I'm getting some extra information in my CSV export that I'd like to remove. Below is my code and an example of what I am seeing.
Code:
NSOutputStream *stream = [[NSOutputStream alloc] initToMemory];
CHCSVWriter *writer = [[CHCSVWriter alloc] initWithOutputStream:stream encoding:NSUTF8StringEncoding delimiter:','];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Notes"];
self.fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:nil];
for (NSString *instance in self.fetchedObjects) {
[writer writeLineOfFields:#[instance.description]];
}
[writer closeStream];
NSData *buffer = [stream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
NSString *output = [[NSString alloc] initWithData:buffer encoding:NSUTF8StringEncoding];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
NSString * csvPath = [documentsDirectory stringByAppendingPathComponent:#"mydata.csv"];
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController * mailView = [[MFMailComposeViewController alloc] init];
mailView.mailComposeDelegate = self;
[[mailView navigationBar] setTintColor:[UIColor whiteColor]];
[mailView setSubject:#"My Subject Line"];
if (![[NSFileManager defaultManager] fileExistsAtPath:csvPath]) {
[[NSFileManager defaultManager] createFileAtPath:csvPath contents:nil attributes:nil];
}
BOOL res = [[output dataUsingEncoding:NSUTF8StringEncoding] writeToFile:csvPath atomically:NO];
if (!res) {
[[[UIAlertView alloc] initWithTitle:#"Error Creating CSV" message:#"Check your permissions to make sure this app can create files so you may email the app data" delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles: nil] show];
} else{
NSLog(#"Data saved! File path = %#", csvPath);
[mailView addAttachmentData:[NSData dataWithContentsOfFile:csvPath] mimeType:#"text/csv" fileName:#"mydata.csv"];
[self presentViewController:mailView animated:YES completion:nil];
}
} else {
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:#"Mail Error" message:#"Your device is not configured to send mail." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
Output Example:
<Notes: 0x1c009fb30> (entity: Notes; id: 0xd000000000080000 <x-coredata://597EDC54-FFDE-43FA-8C61-DE67763C1D13/Notes/p2> ; data: {
// My data shows here.
})
What I want:
I just want the saved data from the user input. Not the extra data about the entity, id, etc.
Also:
My data does not load in the email initially. I have to go into my UIViewController and then when I go to my Settings page and send the email the data shows. What would cause this?
You're getting that result because you're relying the description method to get information about your objects. That method produces a string, and the string is what you're seeing-- something that's not CSV, or easy to convert to CSV.
I'm not familiar with CHCSVParser but it looks like you might want to override description in your Notes class to produce something that CHCSVParser can handle. The default implementation on NSManagedObject-- which is what you're using now-- is not a good choice for this situation.
I am new in iOS and I am facing problem regarding to post string containing special character.
My code is like this in DidFinishLoading:
NSXMLParser *myNSXMLParserPostObj=[[NSXMLParser alloc]initWithData:myNSMDataPostFromServer];
myNSXMLParserPostObj.delegate=self;
[myNSXMLParserPostObj parse];
NSLog(#"%#",myNSXMLParserPostObj.parserError);
NSString *responseStringWithEncoded = [[NSString alloc] initWithData: myNSMDataPostFromServer encoding:NSUTF8StringEncoding];
//NSLog(#"Response from Server : %#", responseStringWithEncoded);
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[responseStringWithEncoded dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
serverResponse.attributedText = attrStr;
NSString *Str =serverResponse.text;
NSLog(#"Server Response =%#",Str);
UIAlertView *alert3 = [[UIAlertView alloc] initWithTitle:#"Success"
message:#"Complaint Added Successfully"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
For getting data from web service I am using code like this:
loginStatusZone = [[NSString alloc] initWithBytes: [myNSMDatazoneFromServer mutableBytes] length:[myNSMDatazoneFromServer length] encoding:NSUTF8StringEncoding];
NSLog(#"loginStatus =%#",loginStatusZone);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:loginStatusZone error:&parseError];
NSLog(#"JSON DICTIONARY = %#",xmlDictionary);
recordResultZone = [xmlDictionary[#"success"] integerValue];
NSLog(#"Success: %ld",(long)recordResultZone);
NSDictionary* Address=[xmlDictionary objectForKey:#"soap:Envelope"];
NSLog(#"Address Dict = %#",Address);
NSDictionary *new =[Address objectForKey:#"soap:Body"];
NSLog(#"NEW DICT =%#",new);
NSDictionary *LoginResponse=[new objectForKey:#"FillZonesNewResponse"];
NSLog(#"Login Response DICT =%#",LoginResponse);
NSDictionary *LoginResult=[LoginResponse objectForKey:#"FillZonesNewResult"];
NSLog(#"Login Result =%#",LoginResult);
if(LoginResult.count>0)
{
NSLog(#"Login Result = %#",LoginResult);
NSLog(#"Login Result Dict =%#",LoginResult);
NSString *teststr =[[NSString alloc] init];
teststr =[LoginResult objectForKey:#"text"];
NSLog(#"Test String Value =%#",teststr);
NSString *string = [LoginResult valueForKey:#"text"];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
zoneresponsedict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
idzonearray=[[NSMutableArray alloc]init];
idzonearray=[zoneresponsedict valueForKey:#"ZoneId"];
NSLog(#"Result Array =%#",idzonearray);
shortnamezonearray=[[NSMutableArray alloc]init];
shortnamezonearray=[zoneresponsedict valueForKey:#"ZoneName"];
NSLog(#"Result Array =%#",shortnamezonearray);
}
If I add special character then it shows me error as
Domain=NSXMLParserErrorDomain Code=111 "The operation couldn’t be completed. (NSXMLParserErrorDomain error 111.)"
How can I post data with special character.
I am adding something like this in Thai language
But I am getting this:
Same with Hindi
Output is getting like this
But when anyone add Thai language using Android or website I get proper text in Thai. Only problem is with this post code.
You can replace your string so that it will allow you to send special character. You can use string method stringByReplacingOccurrencesOfString
NSString *RaisedBy="Your Special character string";
RaisedBy = [RaisedBy stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
RaisedBy = [RaisedBy stringByReplacingOccurrencesOfString:#"<" withString:#"<"];
RaisedBy = [RaisedBy stringByReplacingOccurrencesOfString:#">" withString:#">"];
RaisedBy = [RaisedBy stringByReplacingOccurrencesOfString:#"'" withString:#"'"];
RaisedBy = [RaisedBy stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
This code will also support thai language.
You will need to write the &<> as follows, just like in an html file:
& < >
How to send parameters in json format?
Below are my input parameters :
[
{
"LoginID":151,
"UserID":0,
"SubUserID":0,
"WorkGroupID":92,
"WorksFor":"Doctor",
"UserWorkGroup":0
},
{
"SortingName":"",
"Searching":true,
"SortingOrder":"Desc",
"RecordsCount":10,
"PageIndex":0
}
]
Previously I was sending parameters as below :
[getProfileServices sendSynchronousPostRequestWithStringForAction:getProfileURL andParameters:[[NSDictionary alloc] initWithObjectsAndKeys:#"55",#"LoginID",#"0",#"UserID",#"0",#"SubUserID",#"90",#"WorkGroupID",#"Doctor",#"WorksFor",#"0",#"UserWorkGroup",nil] andRequestType:#"POST"];
how to sent like this but now i need to add some more input mentioned above ?
Just use following code..
NSMutableArray * myArray = [[NSMutableArray alloc]init];
NSMutableDictionary * myData = [[NSMutableDictionary alloc]init];
[myData setValue:#"151" forKey:#"LoginID"];
[myData setValue:#"0" forKey:#"UserID"];
[myData setValue:#"0" forKey:#"SubUserID"];
[myData setValue:#"92" forKey:#"WorkGroupID"];
[myData setValue:#"Doctor" forKey:#"WorksFor"];
[myData setValue:#"0" forKey:#"UserWorkGroup"];
[myArray addObject:myData];
myData = [[NSMutableDictionary alloc]init];
[myData setValue:#"," forKey:#"SortingName"];
[myData setValue:#"1" forKey:#"Searching"];
[myData setValue:#"Desc" forKey:#"SortingOrder"];
[myData setValue:#"10" forKey:#"RecordsCount"];
[myData setValue:#"0" forKey:#"PageIndex"];
[myArray addObject:myData];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"Your final jsonData as string:\n%#", jsonString);
If you want to send this data to Server, then you can use this code:
NSData *dataToSend = [NSJSONSerialization dataWithJSONObject:myArray options:0 error:nil];
[getProfileServices sendSynchronousPostRequestWithStringForAction:getProfileURL andParameters:[[NSDictionary alloc] initWithObjectsAndKeys:dataToSend] andRequestType:#"POST"];
You can do something like this,
NSDictionary *dict1 = #{#"LoginID":#"151",#"UserID":#"0",#"SubUserID":#"0",#"WorkGroupID":#"92",#"WorksFor":#"Doctor",#"UserWorkGroup":#"0"};
NSDictionary *dict2 = #{#"SortingName":#",",#"Searching":#"true",#"SortingOrder":#"Desc",#"RecordsCount":#"10",#"PageIndex":#"0"};
NSArray *arr = [NSArray arrayWithObjects:dict1,dict2, nil];
NSData *dataToSend = [NSJSONSerialization dataWithJSONObject:arr options:0 error:nil];
[getProfileServices sendSynchronousPostRequestWithStringForAction:getProfileURL andParameters:[[NSDictionary alloc] initWithObjectsAndKeys:dataToSend andRequestType:#"POST"];
Hope this will help :)
add it in NSMutableArray and add that array to NSDictionary. like;
{"LoginID":151,"UserID":0,"SubUserID":0,"WorkGroupID":92,"WorksFor":"Doctor","UserWorkGroup":0}
this goes in NSMutableArray and NSMutableArray goes to NSDictionary
Simple way to put array into the dictionary is
#{#[element],#[element],#[element]}
I have an Array of Roll Numbers
NSArray *rollArray = [NSArray arrayWithObjects:#"1", #"22", #"24", #"11", nil];
I need to send this array in a Web Service request
whose format is like this (in JSON format)
JSON data
{
"existingRoll":["22","34","45","56"], // Array of roll numbers
"deletedRoll":["20","34","44","56"] // Array of roll numbers
}
but I am facing problem in converting Array of Roll numbers (rollArray) into json String
in the desired format.
I am trying this
NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];
[postDict setValue:[rollArray componentsJoinedByString:#","] forKey:#"existingRoll"];
NSString *str = [Self convertToJSONString:postDict]; // converts to json string
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:str options:0 error:nil];
[request setHTTPBody:jsonData];
I am using iOS 7
There is no need to use the following code snippets:
[rollArray componentsJoinedByString:#","]
NSString *str = [Self convertToJSONString:postDict];
You can create JSON by using the following code:
NSArray *rollArray = [NSArray arrayWithObjects:#"1", #"22", #"24", #"11", nil];
NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];
[postDict setValue:rollArray forKey:#"existingRoll"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
// Checking the format
NSLog(#"%#",[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
Try this :
NSDictionary *object = #{
#"existingRoll":#[#"22",#"34",#"45",#"56"],
#"deletedRoll":#[#"20",#"34",#"44",#"56"]
};
if ([NSJSONSerialization isValidJSONObject:object]) {
NSData* data = [ NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:nil ];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(str);
}
NSMutableDictionary *postDict = [[NSMutableDictionary alloc] init];
[postDict setValue:#"Login" forKey:#"methodName"];
[postDict setValue:#"admin" forKey:#"username"];
[postDict setValue:#"12345" forKey:#"password"];
[postDict setValue:#"mobile" forKey:#"clientType"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
// Checking the format
NSString *urlString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [[NSString alloc] initWithFormat:#"jsonRequest=%#", urlString];
//#"jsonRequest={\"methodName\":\"Login\",\"username\":\"admin\",\"password\":\"12345\",\"clientType\":\"web\"}";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
You can use following method to get Json string from any type of NSArray :
NSArray *rollArray = [NSArray arrayWithObjects:#"1", #"22", #"24", #"11", nil];
NSData *data = [NSJSONSerialization dataWithJSONObject:rollArray options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Json string is: %#", jsonString);
I am trying to learn how to parse JSON data so I can handle big databases. I wrote code to login into a website.
I have following JSON data from a successful login request:
JSON string : correct username and password [{"user_id":"7","first_name":"dada","last_name":"Kara","e_mail":"yaka#gmail","fullname":"Dada Kara","forum_username":"ycan"}]
and i use following code to parse but it doesnt parse it
-(IBAction)loginButton:(id)sender{
NSString *username = usernameTextfield.text;
NSString *password = passwordTextfield.text;
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:kPostUrl]];
[request setHTTPMethod:#"POST"];
NSString *post =[[NSString alloc] initWithFormat:#"e_mail=%#&password=%#", username, password];
[request setHTTPBody:[post dataUsingEncoding:NSASCIIStringEncoding]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *responseStr = [NSString stringWithUTF8String:[responseData bytes]];
//NSLog(#"Response : %#", responseStr);
NSString *json_string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"JSON string : %#", json_string);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *responseObj = [parser objectWithString:json_string error:nil];
NSArray *name = [responseObj objectForKey:#"first_name"];
NSLog(#"Name : %#", name);
}
The result from my NSLog for name is NULL
Where is the problem and how can I parse such a data so when it comes to lots of rows I can save it to the local FMDB database on iphone
------------------------------EDIT---------------------------------------------------------------
Actual problem was response JSON string from server included echo beginning of the string,json parser only parses between double quotes "", so all i just needed to trim echo from string and parse new string.
and bingo!
//trim in coming echo
NSString *newString1 = [json_string stringByReplacingOccurrencesOfString:#"correct username and password\n" withString:#""];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *responseObj = [parser objectWithString:newString1 error:nil];
NSDictionary *dataDict = [responseObj objectAtIndex:0];
NSString *userID = [dataDict objectForKey:#"user_id"];
NSLog(#"user_id: %#", userID);
output : user_id : 7
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *responseObj = [parser objectWithString:json_string error:nil];
NSDictionary *dataDict = [responseObj objectAtIndex:0];
NSString *name = [dataDict objectForKey:#"first_name"];
Did you print recieve data ? is it showing recieve data from server ? If yes then try with different encoding.
You can use a tool like Objectify ($15 US) or JSON Accelerator ($0.99 US) in the Mac App store to automatically generate data models for you that would make the model as simple as doing object.firstName.