how to pass a NSString from NSObject to UIViewcontrller? - ios

I understand this is a very basic question, but as a beginner who already google a bunch of resources I just couldn't make it. I would like to pass a NSString from a NSObject to UIViewController. I know if want to pass a value to another class I need to make it public. I have a method in DataConnection.m
- (void)jsonParse{
NSString* path = #"http://phdprototype.tk/getResultData.php";
NSURL* url = [NSURL URLWithString:path];
NSString* jsonString = [[NSString alloc]initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
NSDictionary* resultDic = [dic objectForKey:#"maxid"];
NSString* recData = [resultDic objectForKey:#"recommendData"];
NSString* rData = [resultDic objectForKey:#"room"];
NSString* lData = [resultDic objectForKey:#"level"];
NSLog(#"recommendData = %#, room = %#, level = %#",recData,rData,lData);
self->_room = rData;
self->_level = lData;
self->_recommendID = recData;
}
what I want to do is to pass the value of recData to another UIViewController. So I have made a code in 'h:
#property (nonatomic) NSString *recommendID;
in my UIViewController I have this code:
[self.delegate NextScreen: self ndx: recData];
I would like pass value to reData. Anyone tell me how to do that?? sorry for my programme knowledge!
~~~ update~~~
I have put the codes like this:
DataConnection *data = [[DataConnection alloc] init];
[data jsonParse];
[self.delegate NextScreen: self ndx: [data.recommendID]];
but i got expected identifier??

"mmmmmm~i have try some code like DataConnection *data =
[DataConnection jsonParse]; but i got error of no known class method
for selector of "jsonParse" ps: i have put
- (void)jsonParse; in DataConnection.h –"
Above mentioned way is wrong way of calling a method. you can call it this way:
DataConnection *data = [[DataConnection alloc] init];
[data jsonParse];
But, as per your question,
"what I want to do is to pass the value of recData to another
UIViewController. So I have made a code in 'h:"
Change the return type of jsonParse to NSDictionary and return the resultDic which you wish to transfer.
- (NSDictionary *)jsonParse{
NSString* path = #"http://phdprototype.tk/getResultData.php";
NSURL* url = [NSURL URLWithString:path];
NSString* jsonString = [[NSString alloc]initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
NSDictionary* resultDic = [dic objectForKey:#"maxid"];
/* NSString* recData = [resultDic objectForKey:#"recommendData"];
NSString* rData = [resultDic objectForKey:#"room"];
NSString* lData = [resultDic objectForKey:#"level"];
NSLog(#"recommendData = %#, room = %#, level = %#",recData,rData,lData);
self->_room = rData;
self->_level = lData;
self->_recommendID = recData;*/
return resultDic;
}
In your view controller,
#property (nonatomic,retain) NSDictionary *resultDict;
#synthesize resultDict;
DataConnection *data = [[DataConnection alloc] init];
self.resultDict = (NSDictionary *)[data jsonParse];
_recommendID = [resultDic objectForKey:#"recommendData"];
_room = [resultDic objectForKey:#"room"];
_level = [resultDic objectForKey:#"level"];
now recommendID will have the recData value.

have you included
#synthesize recommendID;
in the DataConnection.m file?
I did consider adding this as a comment, but i dont have enough reputation for commenting.

Related

Create JSON format using NSString as a key and values

I have JSON format requirement something like this.
{
"first_name" : "XYZ",
"last_name" : "ABC"
}
I have values in NSString.
NSString strFName = #"XYZ";
NSString strLName = #"ABC";
NSString strKeyFN = #"first_name";
NSString strKeyLN = #"last_name";
And I use NSMutableDictionary
NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];
[dict setObject:strFName forKey:strKeyFN];
[dict setObject:strLName forKey:strKeyLN];
then output is
{
first_name = XYZ,
last_name = ABC
}
So I don't want "=" separating key & values instead I want ":" to separate key and values
I have went most of the stack overflow questions but didn't help getting "=" only in output
So please any help ?
Here is your answer :
NSString *strFName = #"XYZ";
NSString *strLName = #"ABC";
NSInteger number = 15;
NSString *strKeyFN = #"first_name";
NSString *strKeyLN = #"last_name";
NSString *numValue = #"Number";
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
[dic setObject:strFName forKey:strKeyFN];
[dic setObject:strLName forKey:strKeyLN];
[dic setObject:[NSNumber numberWithInt:number] forKey:numValue];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[NSArray arrayWithObject:dic] options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON %#",jsonString);
You write this code after your NSDictionary
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonstr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSString *strFName = #"XYZ";
NSString *strLName = #"ABC";
NSString *strKeyFN = #"first_name";
NSString *strKeyLN = #"last_name";
NSDictionary *ictionary = [NSDictionary dictionaryWithObjectsAndKeys:
strKeyFN, strFName,strKeyLN, strLName,nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"dictionary as string:%#", jsonString);
NSString *strFName = #"ABC";
NSString *strLName = #"XYZ";
NSString *strKeyFN = #"last_name";
NSString *strKeyLN = #"first_name";
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setObject:strFName forKey:strKeyFN];
[dict setObject:strLName forKey:strKeyLN];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[NSArray arrayWithObject:dict] options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStrng = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"Your required JSON is %#",jsonStrng);
try this:-
NSString *cleanedString1 =[strFName stringByReplacingOccurrencesOfString:#"/"" withString:#""];
NSString *cleanedString2 =[strLName stringByReplacingOccurrencesOfString:#"/"" withString:#""];
NSDictionary *Dict = [NSDictionary dictionaryWithObjectsAndKeys:
cleanedString1, strKeyFN,
cleanedString2, strKeyLN,nil];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:Dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
this very robust code to achieve you goal
NSDictionary *userDic = #{strKeyFN:strFName,strKeyLN:strLName};
you have to convert NSMutableDictionary into NSData
then convert the NSData Into json string you want
NSString *strFName = #"XYZ";
NSString *strLName = #"ABC";
NSString *strKeyFN = #"first_name";
NSString *strKeyLN = #"last_name";
NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];
[dict setObject:strFName forKey:strKeyFN];
[dict setObject:strLName forKey:strKeyLN];
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jasonString= [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

JSON String with Arrays iOS

My APP gets a JSON string from a api call JSON string has objects and a array in it. This is what i have done so far but i couldn't get the values from it . advice me please and I'm new to iOS .This is my JSON String :
{
"Id":"0d95a9f6-c763-4a31-ac6c-e22be9832c83",
"Name":"john",
"ProjectName":"project1",
"StartDate":"\/Date(1447200000000)\/",
"Documents":
[{
"Id":"2222a","Name":"book1","ContentType":"application/pdf"
},
{
"Id":"3718e","Name":"Toolbox","ContentType":"application/fillform"
}]
}
Code
NSString *URLString = [NSString stringWithFormat:#"http://mysite/API/Assignments?"];
NSURL *url = [NSURL URLWithString:URLString];
NSData *data=[NSData dataWithContentsOfURL:url];
json=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
assignArray=[[NSMutableArray alloc]init];
for (int i=0; i<json.count; i++) {
NSString *aID=[[json objectAtIndex:i]objectForKey:#"Id"];
NSString *uName=[[json objectAtIndex:i]objectForKey:#"Name"];
NSString *pName=[[json objectAtIndex:i]objectForKey:#"ProjectName"];
//[self initwithUserID:uID userName:uName proName:pName];
// [self retrieveAssignmentDetails:aID];
AssignmentsJson *assignment=[[AssignmentsJson alloc]initwithassignID:aID userName:uName proName:pName];
[assignArray addObject:assignment];
your json is not array so parse like following
NSString *aID = json[#"Id"];
NSString *uName = json[#"Name"];
NSString *pName = json[#"ProjectName"];
NSString *startDate = json[#"StartDate"];
NSArray *documents = json[#"Documents"];
for (NSDictionary *item in documents) {
NSString *itemID = item[#"Id"];
NSString *itemName = item[#"Name"];
NSString *itemContentType = item[#"ContentType"];
}
Your Json Object is NSDictionary. so you can directly get data using valueForKey
NSDictionary *json=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSString *aID = json[#"Id"];
NSString *uName = json[#"Name"];
NSString *pName = json[#"ProjectName"];
for Id,Name and ContentType is inside your array object within your NSDictionary object.
so you can get those values accessing array index.
NSArray *arr = json[#"Documents"];
for (int i=0; i<arr.count; i++) {
NSString *aID=[[arr objectAtIndex:i]objectForKey:#"Id"];
NSString *uName=[[arr objectAtIndex:i]objectForKey:#"Name"];
NSString *cType=[[arr objectAtIndex:i]objectForKey:#"ContentType"];
}
You should learn NSArray and NSDictionary Structure first. it will help you in future. Hope this will help you.
you can do it by following way.
Your Json is in NSDictionary format.
NSData * data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://mysite/API/Assignments?"]];
NSDictionary * dicResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if(dicResponse){
NSString * strID = [dicResponse valueForKey:#"Id"];
NSString * strName = [dicResponse valueForKey:#"Name"];
NSString * strProjectName = [dicResponse valueForKey:#"ProjectName"];
NSString * strDate = [dicResponse valueForKey:#"StartDate"];
NSArray * arrDocuments = [NSArray arrayWithArray:[dicResponse valueForKey:#"Documents"]];
for (int i=0; i< arrDocuments.count; i++) {
NSString * ID=[[arrDocuments objectAtIndex:i]valueForKey:#"Id"];
NSString * Name=[[arrDocuments objectAtIndex:i]valueForKey:#"Name"];
NSString * Type=[[arrDocuments objectAtIndex:i]valueForKey:#"ContentType"];
}
}

Store JSON output in NSArray

Good morning,
I'm trying to develop my first App and I'm using TableView in order to show my entries from a MySQL database and I'm having some trouble when I have to parse the JSON output.
I have already created the connection with my JSON, but now I need to save all the id in a single Array, all the user in another array, etc, etc. As you can see below in my second code, I need to store them in a NSArray. How can I do that?
That's my JSON
[{"id":"15","user":"1","imagen":"http:\/\/farmaventas.es\/images\/farmaventaslogo.png","date":"2014-09-13"}
,{"id":"16","user":"2","imagen":"http:\/\/revistavpc.es\/images\/vpclogo.png","date":"2014-11-11"}]
And that's my TableViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// Here I have to store my "user"
self.carMakes = [[NSArray alloc] initWithObjects: nil];
// Here I have to store my "imagen"
self.carModels = [[NSArray alloc] initWithObjects: nil];
}
Thanks in advance.
That's another solution with KVC
NSArray *carMakes = [json valueForKeyPath:#"#unionOfObjects.id"];
NSArray *carModels = [json valueForKeyPath:#"#unionOfObjects.user"];
First of all, you would want to fetch JSON on another thread, so you dont block your main thread with it:
#interface ViewController ()
#end
#implementation ViewController
-(void)viewDidLoad
{
[super viewDidLoad];
[self fetchJson];
}
-(void)fetchJson {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// I advice that you make your carModels mutable array and initialise it here,before start working with json
self.carModels = [[NSMutableArray alloc] init];
#try {
NSError *error;
NSMutableArray* json = [NSJSONSerialization
JSONObjectWithData:theData
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
if (error){
NSLog(#"%#",[error localizedDescription]);
}
else{
for(int i=0;i<json.count;i++){
NSDictionary * jsonObject = [json objectAtIndex:i];
NSString* imagen = [jsonObject objectForKey:#"imagen"];
[carModel addObject:imagen];
}
dispatch_async(dispatch_get_main_queue(), ^{
// If you want to do anything after you're done loading json, do it here
}
});
}
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// Here you have to store my "user"
self.userArray = [[NSMutableArray alloc]init];
for (NSDictionary *userInfo in json){
//get "user" from json
NSString* user = [userInfo objectForKey:#"user"];
//add to array
[userArray addObject:user];
}
You have use NSMutableArray to add object instead.
Since "json" is array of NSDictionary you can get iterate over it and add to arrays like this:
NSArray *json = #[#{#"id":#"15",#"user":#"1",#"imagen":#"http:\/\/farmaventas.es\/images\/farmaventaslogo.png",#"date":#"2014-09-13"},
#{#"id":#"16",#"user":#"2",#"imagen":#"http:\/\/revistavpc.es\/images\/vpclogo.png",#"date":#"2014-11-11"}];
NSArray *carMakes = [NSArray array];
NSArray *carModels = [NSArray array];
for (NSDictionary *dict in json) {
carMakes = [carMakes arrayByAddingObject:dict[#"id"]];
carModels = [carModels arrayByAddingObject:dict[#"user"]];
}
NSLog(#"%#",carMakes);
NSLog(#"%#",carModels);

Using NSArray and NSDictionary to access a JSON object without a root element

Here's an example of my data:
[
{
code: "DRK",
exchange: "BTC",
last_price: "0.01790000",
yesterday_price: "0.01625007",
top_bid: "0.01790000",
top_ask: "0.01833999"
}
]
I'm trying to retrieve the value for last_price by loading the contents of my NSDictionary into an Array.
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSDictionary *darkDict = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
self.darkPosts = [NSMutableArray array];
NSArray *darkPostArray = [darkDict objectForKey:#""];
for (NSDictionary *darkDict in darkPostArray) {...
But my json doesn't have a root element, so what do I do?
Additionally, when using the suggested answer, the output is ("...
- (void)viewDidLoad{
[super viewDidLoad];
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSDictionary *darkDict = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
NSString *lastP = [darkDict valueForKey:#"last_price"];
self.dark_label.text = [NSString stringWithFormat: #"%#", lastP];
}
It looks like you are wanting to iterate over your results. The root element is an array not a dictionary so you can just start iterating
NSError *error = nil;
NSArray *items = [NSJSONSerialization JSONObjectWithData:darkData
options:kNilOptions
error:&error];
if (!items) {
NSLog(#"JSONSerialization error %#", error.localizedDescription);
}
for (NSDictionary *item in items) {
NSLog(#"last_price => %#", item[#"last_price"]);
}
If you literally just want to collect an array of the last_price's then you can so this
NSArray *lastPrices = [items valueForKey:#"last_price"];
Convert the JSON to an NSArray with NSJSONSerialization. Then access the value:
NSData *darkData = [#"[{\"code\":\"DRK\",\"exchange\": \"BTC\",\"last_price\": \"0.01790000\",\"yesterday_price\": \"0.01625007\",\"top_bid\": \"0.01790000\"}, {\"top_ask\": \"0.01833999\"}]" dataUsingEncoding:NSUTF8StringEncoding];
NSArray *array = [NSJSONSerialization JSONObjectWithData:darkData
options:0
error:&error];
NSString *value = array[0][#"last_price"];
NSLog(#"value: %#", value);
NSLog output:
value: 0.01790000
If you are having trouble post the code you have written to get some help.
-- updated for new OP code:
The web service returns a JSON array or dictionaries not a JSON dictionary. First you have to index into the array and then index into the dictionary.
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSArray *darkArray = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
NSDictionary *darkDict = darkArray[0];
NSString *lastP = [darkDict valueForKey:#"last_price"];
NSLog(#"lastP: %#", lastP);
NSLog output:
lastP: 0.01970000
Note that the two lines:
NSDictionary *darkDict = darkArray[0];
NSString *lastP = [darkDict valueForKey:#"last_price"];
can be replaced with the single line using array indexing:
NSString *lastP = darkArray[0][#"last_price"];
Where the "[0]" gets the first array element which is a NSDictionary and the "[#"last_price"]" gets the names item from the dictionary.

Retrieve data from NSMutableArray

I am only starting with IOS Development and creating an IOS application (Final project) for my computer science class which uses JSON to get data from remote MySql database.
Here is the method I call from ViewDidLoad:
- (void)loadJSON
{
//-- Make URL request with server
NSHTTPURLResponse *response = nil;
NSString *jsonUrlString = [NSString stringWithFormat:#"http://vito-service.ru/studentsconnect/profile.php"];
NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//-- Get request and response though URL
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
//-- JSON Parsing
NSMutableArray *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Result = %#",result);
}
and NSLog prints the correct data:
Result = {
users = (
{
IdUser = 1;
facebook = "";
fullname = "";
instagram = "";
phonenumber = "";
username = moderas;
},
{
IdUser = 2;
facebook = "fb.com/petroffmichael";
fullname = "Michael Perov";
instagram = "#petroffmichael";
phonenumber = "(650)557-6168";
username = petroffmichael;
},
{
IdUser = 3;
facebook = "fb.com/testuser";
fullname = "Test User";
instagram = "#testuser";
phonenumber = "111 111-1111";
username = testuser;
}
);
}
But how can I retrieve this data as Strings to put them to the labels then? I tried lots of different options of creating Data objects, which I found here on stack overflow but I always get an "unrecognized selector sent to instance" error. I also tried creating a separate NSObject
#synthesize IdUser, username, fullname, phonenumber, facebook, instagram;
- (id) initWithUsername: (NSString *)uUsername andUserFullName: (NSString *)uFullname andUserPhonenumber: (NSString *)uPhonenumber andUserFacebook: (NSString *)uFacebook andUserInstagram: (NSString *)uInstagram andUserId: (NSString *)uId
{
self = [super init];
if (self) {
username = uUsername;
fullname = uFullname;
phonenumber = uPhonenumber;
facebook = uFacebook;
instagram = uInstagram;
IdUser = uId;
}
return self;
}
and then retrieving data with this method:
-(void)retrieveData
{
NSURL *url = [NSURL URLWithString:getDataUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
usersArray = [[NSMutableArray alloc] init];
for (int i=0; i<jsonArray.count; i++) {
NSString * uId = [[jsonArray objectAtIndex: i] objectForKey:#"IdUser"];
NSString * uUsername = [[jsonArray objectAtIndex: i] objectForKey:#"username"];
NSString * uFullname = [[jsonArray objectAtIndex: i] objectForKey:#"fullname"];
NSString * uPhonenumber = [[jsonArray objectAtIndex: i] objectForKey:#"phonenumber"];
NSString * uFacebook = [[jsonArray objectAtIndex: i] objectForKey:#"facebook"];
NSString * uInstagram = [[jsonArray objectAtIndex: i] objectForKey:#"instagram"];
[usersArray addObject:[[User alloc] initWithUsername:uUsername andUserFullName:uFullname andUserPhonenumber:uPhonenumber andUserFacebook:uFacebook andUserInstagram:uInstagram andUserId:uId]];
}
}
I have all the important #import's but I still get the same error:
2014-04-23 18:35:26.612 testimage[47155:70b] -[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0xa72a8b0
2014-04-23 18:35:26.813 testimage[47155:70b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0xa72a8b0'
Can anybody please help to find the right solution?
Thanks!
After listening to multiple comments I changed the code but still receive an error..
I guess I am still doing something wrong
jsonArray is not an array anymore:
#property (nonatomic, strong) NSDictionary *jsonArray;
#property (nonatomic, strong) NSMutableArray *usersArray;
Then the method:
-(void)retrieveData
{
NSURL *url = [NSURL URLWithString:getDataUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
usersArray = [[NSMutableArray alloc] init];
for (NSDictionary *dict in jsonArray)
{
NSString * uId = [dict objectForKey:#"IdUser"];
NSString * uUsername = [dict objectForKey:#"username"];
NSString * uFullname = [dict objectForKey:#"fullname"];
NSString * uPhonenumber = [dict objectForKey:#"phonenumber"];
NSString * uFacebook = [dict objectForKey:#"facebook"];
NSString * uInstagram = [dict objectForKey:#"instagram"];
[usersArray addObject:[[User alloc] initWithUsername:uUsername andUserFullName:uFullname andUserPhonenumber:uPhonenumber andUserFacebook:uFacebook andUserInstagram:uInstagram andUserId:uId]];
}
}
And I am still getting the same error:
2014-04-23 20:44:43.971 testimage[48285:70b] -[__NSCFString objectForKey:]: unrecognized selector sent to instance 0xa5547d0
2014-04-23 20:44:44.053 testimage[48285:70b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0xa5547d0'
Look closely at that output. It isn't what you say. What you have there is not an array — it's a dictionary with one key, #"users", whose value is an array. That's what it's telling you when it starts with { users = …. If you want the array, you'll need to retrieve it from the dictionary.
Try this:
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSMutableArray *result = [res objectForKey:#"users"];
This will do. The response isn't a NSArray. It is a Dictionary. First get the array from the dictionary and then use it as you are using. Hope this helps... :)
EDIT:
You can rewrite the loop by this:
for (NSDictionary *dict in jsonArray)
{
//dict is a NSDictionary. Just get value for keys
}

Resources