Not able to print my json data in my console? - ios

here is my code. I used NSDictionary and coded to print my json data in my console.but i got error like this:
'NSInvalidArgumentException', reason: '-[__NSCFString objectForKeyedSubscript:]: unrecognized selector sent to instance 0x7c971930'
My code:
if(buttonIndex == 0) {
NSLog(#"OK Button is clicked");
}
else if(buttonIndex == 1) {
if([[textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]!=0)
{
if(!self.note)
{
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newNote = [NSEntityDescription insertNewObjectForEntityForName:#"Notes" inManagedObjectContext:context];
NSLog(#"%#",textView.text);
[newNote setValue:textView.text forKey:#"note"];
if([textView.text length]>30)
{
[newNote setValue:[NSString stringWithFormat:#"%#...",[textView.text substringToIndex:25]] forKey:#"title"];
}
else
[newNote setValue:textView.text forKey:#"title"];
[newNote setValue:[NSDate date] forKey:#"mod_time"];
//[newDevice setValue:self.versionTextField.text forKey:#"version"];
//[newDevice setValue:self.companyTextField.text forKey:#"company"];
How to overcome this problem to work and to print my data in my console
Help me out. I am struggling for 2 hours.I googled and change all change.But cant get data in my console. Thanks in advance

I guess you can get data like below this
NSDictionary *monday = jsonResults[#"original"];
NSArray * arrFile = monday[#"files"];
for (NSDictionary *theCourse in arrFile)
{
....
}

Did you checked that received data (i.e., returnData) from sendSynchronousRequest: is returning a plain data?
If the data received is in Base64, you might have to decode this NSData to plain data, and then go ahead with String conversion.
NSData *decodedData = [[NSData alloc] initWithBase64EncodedData:responseData options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSString *str = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];

// convert Json to NSDictionary
NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
// NSLog(#"%#",jsonResults);
int count = [[jsonResults valueForKey:#"count"] intValue];
NSArray *arrayData = [jsonResults copy];
NSMutableArray *arrayPDFName = [[NSMutableArray alloc]init];
for(int i = 0;i < [arrayData count];i++)
{
NSDictionary *dictOriginal = [[arrayData objectAtIndex:2]valueForKey:#"original"];
int countOriginal = [[dictOriginal valueForKey:#"count"] intValue];
NSLog(#"The countOriginal is - %d",countOriginal);
NSArray *arrayFiles = [[dictOriginal valueForKey:#"files"] copy];
NSLog(#"The arrayFiles are - %#",arrayFiles);
for(int j=0;j<[arrayFiles count];j++)
{
NSString *strCreatedTime = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:j] valueForKey:#"created_time"]];
NSString *strLastModifiedTime = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:j] valueForKey:#"last_modified_time"]];
NSString *strID = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:j] valueForKey:#"id"]];
NSString *strName = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:j] valueForKey:#"name"]];
NSLog(#"The created_time is - %#",strCreatedTime);
NSLog(#"The last_modified_time is - %#",strLastModifiedTime);
NSLog(#"The is is - %#",strID);
NSLog(#"The name is - %#",strName);
[arrayPDFName addObject:strName];
}
}

Related

add string dynamically in objc

I want to add string value dynamically from result.text and I wanted to display it in this way [#"17052648287",#"17052607335"] without losing the value. How can I do it?
NSMutableArray *strings = [#[#"17052648287",#"17052607335"] mutableCopy];
Add on coding
- (void)captureResult:(ZXCapture *)capture result:(ZXResult *)result{
if (!result) return;
if(self.hasScannedResult == NO)
{
//Scan Result, added into array
NSString *scanPackage = [NSString stringWithFormat:#"%#", result.text];
scanLists = [NSMutableArray new];
[scanLists addObject:scanPackage];
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
NSMutableArray *strings = [[NSMutableArray alloc]init];
strings = [#[result.text] mutableCopy];
[preferences setObject:strings forKey:#"strings"];
NSMutableArray *stringsArray = [preferences objectForKey:#"strings"];
for (NSString *string in stringsArray) {
NSLog(#"string: %#", string);
}
Declare an results array:
NSMutableArray * array = [NSMutableArray new];
Write below code where you get your result.text:
NSString *scanPackage = [NSString stringWithFormat:#"%#", result.text]; // If this code is working for you
[array addObject: scanPackage];
NSString *combined = [array componentsJoinedByString:#","];
NSLog(#"combined: %#", combined);

data disappear out of UNIUrlConnection

What I'm trying to do is to pass data from my Objective-C to my swift file.
Recently, when I have successfully connected my objective c file with my swift file, I can print data that get from UNIUrlConnection(which means the connection between swift and objective-c works fine).
Then I create a NSMutableDictionary object and add those data into NSMutableDictionary. I want to pass this NSMutableDictionary object to my swift file so that I can output them on my viewController.
However, the NSMutableDictionary contains correct data within the UNIUrlConnection but then contains none out of UNIUrlConnection. Thus the NSMutableDictionary passed to swift file would always contain no data. How can I solve this?
This is my objective c file.
#import <Foundation/Foundation.h>
#import <UNIRest.h>
#import "findByIngredients.h"
#implementation findByIngredients
-(NSMutableDictionary*) connectAPI:(NSString*) ingredients Number:(NSString*) number{
NSMutableDictionary *temp = [NSMutableDictionary dictionaryWithCapacity:10];
NSString* url = #"https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients?fillIngredients=false";
if (![ingredients isEqual: #""]) {
NSString* ingre = #"&ingredients=";
ingre = [ingre stringByAppendingString:ingredients];
url = [url stringByAppendingString:ingre];
}
else {
NSString* ingre = #"&ingredients=<required>";
url = [url stringByAppendingString:ingre];
}
NSString* LL = #"&limitLicense=false";
url = [url stringByAppendingString:LL];
if (![number isEqual: #""]) {
NSString* numberOfReturn = #"&number=";
numberOfReturn = [numberOfReturn stringByAppendingString:number];
url = [url stringByAppendingString:numberOfReturn];
}
NSString* ranking = #"&ranking=1";
url = [url stringByAppendingString:ranking];
// These code snippets use an open-source library. http://unirest.io/objective-c
NSDictionary *headers = #{#"X-Mashape-Key": #"KEY", #"Accept": #"application/json"};
UNIUrlConnection *asyncConnection = [[UNIRest get:^(UNISimpleRequest *request) {
[request setUrl:url];
[request setHeaders:headers];
}] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
NSInteger code = response.code;
NSDictionary *responseHeaders = response.headers;
UNIJsonNode *body = response.body;
NSData *rawBody = response.rawBody;
if (rawBody) {
id allKeys = [NSJSONSerialization JSONObjectWithData:rawBody options:0 error:&error];
for (int i=0; i<[allKeys count]; i++) {
NSDictionary *arrayResult = [allKeys objectAtIndex:i];
// NSString* myNewString = [NSString stringWithFormat:#"%d", i];
NSString *key = [arrayResult objectForKey:#"id"];
NSString *value = [arrayResult objectForKey:#"title"];
[temp setObject:value forKey:key];
NSLog(#"id=%#",[arrayResult objectForKey:#"id"]);
NSLog(#"title=%#",[arrayResult objectForKey:#"title"]);
}
}
int size = [temp count];
NSLog(#"temp size is %d",size);
NSLog(#"successfully test API");
}];
// int size = [temp count];
// NSLog(#"temp size is %d",size);
return temp;
}
#end
Here the size of temp within UNIUrlConnection is correct. But if I put the size before return (which I comment out), it shows 0, which is wrong.
This is my swift file.
#IBAction func search(_ sender: Any) {
let ingreArr = IngredientsText.text.components(separatedBy: [",", " "])
var ingre:String = ingreArr[0]
let sep:String = "%2C"
for (index,element) in ingreArr.enumerated() {
if (index >= 1) {
ingre = ingre + sep + element
}
}
let test = findByIngredients()
// test.connectAPI(ingre, number: NumberOfResults.text)
let result: Dictionary = test.connectAPI(ingre, number: NumberOfResults.text) as Dictionary
let num:Int = result.count
print(num)
}
The num is 0.

Can't extract needed information from NSDictionary

I parse a XML file, and after parsing get a NSDictionary object (XMLDictionary named). I'm parsing this:
<result><node><id>27</id><name>Name 1</name><type>0</type><price>0</price><img>/upload/iblock/1a1/1a138b2d4da6e42398beeb21acc8e84f.png</img></node><node><id>28</id><name>Name 2</name><type>0</type><price>0</price><img>/upload/iblock/b72/b724d1550f93987a73b04974b5f7390e.png</img></node></result>
After that i'm trying this (titleArr - NSArray):
_titleArr = [[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"node"] objectForKey:#"name"] valueForKey:#"text"];
In Run-time I get this error in the above line: "Thread 1: signal SIGABRT". How can i fix this problem?
NSError* parseError = nil;
_xmlDictionary = [XMLReader dictionaryForXMLString:myXMLString error:&parseError];
if (parseError != nil) {
NSLog(#"Error on XML parse: %#", parseError);
}
NSLog(#"The full dictionary is %#", _xmlDictionary);
NSDictionary* result = [_xmlDictionary objectForKey:#"result"];
NSLog(#"'result' = %#", result);
NSDictionary* node = [result objectForKey:#"node"];
NSLog(#"'node' = %#", node);
NSString* name = [node objectForKey:#"name"];
NSLog(#"'name' = %#", name);
At the very least, if it fails, the error will be isolated to a single operation. And the NSLogs will show you the values after each step.
Try this:
NSArray *arrResult = [_xmlDictionary objectForKey:#"result"];
for(int i = 0; i < [arrResult count]; i++)
{
NSArray *arrNode = [arrResult objectAtIndex:i] valueForKey:#"node"];
NSString *sName = [arrNode valueForKey:#"Name"];
NSLog(#"Name : %#",sName);
}
Edited Answer
NSArray *arrResult = [_xmlDictionary valueForKey:#"result"];
for (int i = 0; i < [arrResult count]; i++) {
NSDictionary *dicNode = [[arrResult objectAtIndex:i] valueForKey:#"Node"];
NSString *sName = [dicNode valueForKey:#"Name"];
NSLog(#"Name : %#",sName);
}

Parsing a JSON string into three arrays Objective C

I am trying to use the data which I read from a text file in objective c. The data I read from the text file is:
{"aps":{"alert":"Test 1!","sound":"beep.wav","badge":5,"Type":"Banking"},"acme1":"bar","acme2":42}|{"aps":{"alert":"Test 2!","sound":"beep.wav","badge":5,"Type":"Banking"},"acme1":"bar","acme2":42}|{"aps":{"alert":"Test 3!","sound":"beep.wav","badge":5,"Type":"Banking"},"acme1":"bar","acme2":42}|{"aps":{"alert":"Test 4!","sound":"beep.wav","badge":5,"Type":"Banking"},"acme1":"bar","acme2":42}|{"aps":{"alert":"Test 5!","sound":"beep.wav","badge":5,"Type":"Banking"},"acme1":"bar","acme2":42}
Once read, I split the file into an array with a delimiter of "|". I then want to further separate it into 3 different arrays: banking, fraud and investment based on the key "Type". However I cannot seem to reach parse the JSON string once I split it into the array. My view did load method is below:
- (void)viewDidLoad {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/AccountNotifications.txt", documentsDirectory];
NSString *fileContents = [[NSString alloc] initWithContentsOfFile:fileName usedEncoding:nil error:nil];
NSArray *fileData = [fileContents componentsSeparatedByString:#"|"];
if (fileContents != NULL)
{
bankingNotifications = [[NSMutableArray alloc] init];
fraudNotifications = [[NSMutableArray alloc] init];
investmentNotifications = [[NSMutableArray alloc] init];
for (i = 0; i < [fileData count]; i++)
{
NSString *notification = fileData[i];
NSDictionary *json = [notification JSONValue];
NSArray *items = [json valueForKeyPath:#"aps"];
if ([[[items objectAtIndex:i] objectForKey:#"Type"] isEqual: #"Banking"])
{
[bankingNotifications addObject:fileData[i]];
NSLog(#"Added object to banking array");
}
if ([[[items objectAtIndex:i] objectForKey:#"Type"] isEqual: #"Fraud"])
{
[fraudNotifications addObject:fileData[i]];
NSLog(#"Added object to fraud array");
}
if ([[[items objectAtIndex:i] objectForKey:#"Type"] isEqual: #"Investment"])
{
[investmentNotifications addObject:fileData[i]];
NSLog(#"Added object to investment array");
}
} }
There is an error with these three lines:
NSString *notification = fileData[i];
NSDictionary *json = [notification JSONValue];
NSArray *items = [json valueForKeyPath:#"aps"];
Could you please help me parse the JSON strings into the three mutable arrays? The error I am getting is:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryM objectAtIndex:]: unrecognized selector sent to instance 0x1d59db30'
If you create the text file yourself I would suggest you create a valid json object (as your data looks like it is supposed to be json) to keep your data nice and clean. similar to this:
{"aps":[{"type":"Banking","badge":5},{"Type":"Fraud","badge":12}]}
Then you can do following (this code is not tested, it can be that you have to amend it a bit) but i hope you'll get an idea :)
NSError* error = nil;
NSDictionary* dict = nil;
//serialising the jsonobject to a dictionary
dict = [NSJSONSerialization JSONObjectWithData:fileContents
options:kNilOptions
error:&error];
bankingNotifications = [[NSMutableArray alloc] init];
fraudNotifications = [[NSMutableArray alloc] init];
investmentNotifications = [[NSMutableArray alloc] init];
if (dict) {
NSArray *dataArray = [dict objectForKey:#"aps"];
NSDictionary* siteData = nil;
NSEnumerator* resultsEnum = [dataArray objectEnumerator];
while (siteData = [resultsEnum nextObject])
{
//
if( [[siteData objectForKey:#"Type"] isEqualToString: #"Banking"]) {
[bankingNotifications addObject:notification];
NSLog(#"Added object to banking array");
} else if ([[siteData objectForKey:#"Type"] isEqualToString: #"Fraud"])
{
[fraudNotifications addObject:notification];
NSLog(#"Added object to fraud array");
}
else if ([[siteData objectForKey:#"Type"] isEqualToString: #"Investment"])
{
[investmentNotifications addObject:notification];
NSLog(#"Added object to investment array");
}
}
}
The value for Key "aps" is a dictionary.
NSDictionary *item = [json valueForKeyPath:#"aps"];
if ([[item objectForKey:#"Type"] isEqualToString: #"Banking"])
{
[bankingNotifications addObject:notification];
NSLog(#"Added object to banking array");
}
else if ([[item objectForKey:#"Type"] isEqualToString: #"Fraud"])
{
[fraudNotifications addObject:notification];
NSLog(#"Added object to fraud array");
}
else if ([[item objectForKey:#"Type"] isEqualToString: #"Investment"])
{
[investmentNotifications addObject:notification];
NSLog(#"Added object to investment array");
}

How do I convert an LDAP "jpegPhoto" to NSString to UIImageView

I am trying to pull an LDAP "jpegPhoto" attribute from an openLDAP server using a iOS openLDAP framework. The framework pulls the data as a dictionary of NSStrings.
I need to convert the NSString of "jpegPhoto" (which also appears to be base64 encoded) to UIImage, with the end result being that I display the jpegPhoto as the user's image when they login.
More Info:
-(NSDictionary *)doQuery:(NSString *)query:(NSArray *)attrsToReturn {
...
while(attribute){
if ((vals = ldap_get_values_len(ld, entry, attribute))){
for(int i = 0; vals[i]; i++){
//Uncomment if you want to see all the values.
//NSLog(#"%s: %s", attribute, vals[i]->bv_val);
if ([resultSet objectForKey:[NSString stringWithFormat:#"%s",attribute]] == nil){
[resultSet setObject:[NSArray arrayWithObject:[NSString stringWithFormat:#"%s",vals[i]->bv_val]] forKey:[NSString stringWithFormat:#"%s",attribute]];
}else{
NSMutableArray *array = [[resultSet objectForKey:[NSString stringWithFormat:#"%s",attribute]] mutableCopy];
[array addObject:[NSString stringWithFormat:#"%s",vals[i]->bv_val]];
[resultSet setObject:array forKey:[NSString stringWithFormat:#"%s",attribute]];
}
}
ldap_value_free_len(vals);
};
ldap_memfree(attribute);
attribute = ldap_next_attribute(ld, entry, ber);
};
...
}
-(UIIMage *)getPhoto{
NSString *query = [NSString stringWithFormat:#"(uid=%#)",self.bindUsername];
NSArray *attrsToReturn = [NSArray arrayWithObjects:#"cn",#"jpegPhoto", nil];
NSDictionary *rs = [self doQuery:query:attrsToReturn];
NSString *photoString = [[rs objectForKey:#"jpegPhoto"] objectAtIndex:0];
NSLog(#"The photoString is: %i %#",[photoString length],#"characters long"); //returns 4
NSData *photoData = [NSData dataWithBase64EncodedString:photoString];
UIImage *userPhoto = [UIImage imageWithData:photoData];
return userPhoto;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.studentNameLabel.text = [NSString stringWithFormat:#"Hi %#!",[self.ldap getFullName]];
self.studentPhotoImage.image = [self.ldap getPhoto];
[self checkForProctor];
}
Try this code
NSData *dataObj = [NSData dataWithBase64EncodedString:beforeStringImage];
UIImage *beforeImage = [UIImage imageWithData:dataObj];
There are many similar questions in Stackoverflow.. Please refer the following links
UIImage to base64 String Encoding
UIImage from bytes held in NSString
(Since there has been no working code posted for getting the image data from LDAP, I wanted to add this answer for the benefit of future visitors.)
The missing piece was reading the binary data into an NSData object rather than an NSString when you have binary data that might contain NULL (zero) values within it, such as images or GUIDs.
value = [NSData dataWithBytes:vals[0]->bv_val length:vals[0]->bv_len];
+ (NSArray *)searchWithBaseDN:(const char *)baseDN andFilter:(const char *)filter andScope:(int)scope {
...
while(entry)
{
// create a dictionary to hold attributes
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
attribute = ldap_first_attribute(ld, entry, &ber);
while(attribute)
{
if ((vals = ldap_get_values_len(ld, entry, attribute)))
{
if (ldap_count_values_len(vals) > 1) {
NSMutableArray *values = [[NSMutableArray alloc] init];
for(int i = 0; vals[i]; i++) {
[values addObject:[NSString stringWithUTF8String:vals[i]->bv_val]];
}
[dictionary setObject:values forKey:[NSString stringWithUTF8String:attribute]];
} else {
NSObject *value = nil;
if (strcmp(attribute, "thumbnailPhoto") == 0 || strcmp(attribute, "objectGUID") == 0) {
value = [NSData dataWithBytes:vals[0]->bv_val length:vals[0]->bv_len];
} else {
value = [NSString stringWithFormat:#"%s", vals[0]->bv_val];
}
[dictionary setObject:value forKey:[NSString stringWithUTF8String:attribute]];
}
ldap_value_free_len(vals);
};
ldap_memfree(attribute);
attribute = ldap_next_attribute(ld, entry, ber);
};
...
}

Resources