Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

IDMah

macrumors 6502
Original poster
May 13, 2011
317
11
Hi all Nob Question... of the day.

I'd like to take an array of High Score Objects, and send them all as one JSON Array. I can do this right?

Here's what I have so far. I'm definitely confused as the code probably tells, and not sure I'm even approaching this correctly..

Code:
-(void) sendQuedItemsNow
{
    NSLog(@"Sending Qued Data");
      
    NSURL *url = [NSURL URLWithString:@"http://localhost"]; 
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
    
    // SingletonCentre is a singleton that holds the mutable array myQuedHighScores 
    // which holds HighScoreKeeper objects I want to send //

    SingletonCentre *sharedHSData = [SingletonCentre sharedSingleton];
    
    NSMutableArray* sendAllJSONDICT = [[NSMutableArray alloc]init];
    NSLog(@"Found Qued HighScores: %i",[sharedHSData.myQuedHighScores count]);
    
    for (HighScoreKeeper *myHighscoreToSend in sharedHSData.myQuedHighScores ) {
        NSLog(@"name: %@ time: %@ gametime: %i",myHighscoreToSend.name,myHighscoreToSend.gameTime,
          myHighscoreToSend.gameTimeSeconds);
        
        NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                                myHighscoreToSend.name,@"userName",
                                myHighscoreToSend.gameTime,@"userID",
                                [NSNumber numberWithInt:myHighscoreToSend.gameTimeSeconds],@"score",
                                nil];

        [sendAllJSONDICT addObject:params];
        
       
    }    
   NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendAllJSONDICT options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
   
 NSLog(@"jsonData sending string:\n%@", jsonString);  
    
 // ***What do I do now.???? Defiantly where I'm stuck !! **** //
  NSDictionary *paramsit = [NSDictionary dictionaryWithObjectsAndKeys:@{jsonString,nil}];
 
    [httpClient postPath:@"/registar_working_score.php" parameters:paramsit success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"Request Successful, response '%@'", responseStr);
        sharedHSData.queuedItems--;
        // if the HighScore was sent then return YES if not NO //
        sharedHSData.errorUploading=NO;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"OKTOUPDATEHIGHSCORES" object:nil];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
        sharedHSData.errorUploading=YES; 
        [[NSNotificationCenter defaultCenter] postNotificationName:@"SHOWMETHESTATUSE" object:nil];
        
    }];
}

Here's the output:

Code:
2013-10-12 15:46:59.294 UIScrollView-Paging-networked[3567:207] Sending Qued Data
2013-10-12 15:46:59.301 UIScrollView-Paging-networked[3567:207] Found Qued HighScores: 4
2013-10-12 15:46:59.302 UIScrollView-Paging-networked[3567:207] name: UghBugs time: 00:08:01 gametime: 481
2013-10-12 15:46:59.302 UIScrollView-Paging-networked[3567:207] name: 1 UghBugs time: 00:08:02 gametime: 0
2013-10-12 15:46:59.302 UIScrollView-Paging-networked[3567:207] name: 2 UghBugs time: 00:08:03 gametime: 0
2013-10-12 15:46:59.302 UIScrollView-Paging-networked[3567:207] name: 3 UghBugs time: 00:08:32 gametime: 0
2013-10-12 15:46:59.303 UIScrollView-Paging-networked[3567:207] jsonData sending string:
[
  {
    "userName" : "UghBugs",
    "userID" : "00:08:01",
    "score" : 481
  },
  {
    "userName" : "1 UghBugs",
    "userID" : "00:08:02",
    "score" : 0
  },
  {
    "userName" : "2 UghBugs",
    "userID" : "00:08:03",
    "score" : 0
  },
  {
    "userName" : "3 UghBugs",
    "userID" : "00:08:32",
    "score" : 0
  }
]
2013-10-12 15:46:59.304 UIScrollView-Paging-networked[3567:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSDictionary dictionaryWithObjectsAndKeys:]: second object of each pair must be non-nil.  Or, did you forget to nil-terminate your parameter list?'
 
Last edited:
Good lord mate, your code is a mess :p

Why do you need this?

Code:
NSDictionary *paramsit = [NSDictionary dictionaryWithObjectsAndKeys:@{jsonString,nil}];

You got your json string already, no need to put it into a NSDictionary, plus its wrong!
 
I know.. Sorry!!! I'm new to all this..

But:
Code:
    [httpClient postPath:@"/registar_working_score.php" parameters:paramsit success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

Seems to want a NSDictionary for parameters. SO I was Grasping at straws.

I think I found what I needed.

Code:
// for nubes like me I think this just casts a string as a dictionary 
NSDictionary *paramss =(NSDictionary *)jsonString;

Now I just have to modify PHP to receive a JSON Array.
 
Last edited:
I know.. Sorry!!! I'm new to all this..

But:
Code:
    [httpClient postPath:@"/registar_working_score.php" parameters:paramsit success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

seems to want a NSDictionary for parameters. SO I'm Grasping at straws.

Haha no problem :p

This should be enough to send a post request:

Code:
    NSData *payloadData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"[B]YOUR FULL URL[/B]"]];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:payloadData];
    
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               
                               NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                               
                              //Check the contents of responseString

                           }];
 
// ***What do I do now.???? Defiantly where I'm stuck !! **** //
Code:
NSDictionary *paramsit = [NSDictionary dictionaryWithObjectsAndKeys:@{jsonString,nil}];

You start by reading the documentation for NSDictionary dictionaryWithObjectsAndKeys:. That will allow you to fix the exception.

According the docs, the AFNetworking method you are using does require a NSDictionary, so you are are correct to build it.

It has been a while, but I think you can just place your jsonData into that dictionary as a value. I don't think converting it to a NSString has any value. I'll leave that to you to experiment with.

As for the rest of it, I don't know. I didn't dig that deep.
 
Hi all Nob Question... of the day.

I'd like to take an array of High Score Objects, and send them all as one JSON Array. I can do this right?

Here's what I have so far. I'm definitely confused as the code probably tells, and not sure I'm even approaching this correctly..

Code:
-(void) sendQuedItemsNow
{
    NSLog(@"Sending Qued Data");
      
    NSURL *url = [NSURL URLWithString:@"http://localhost"]; 
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
    
    // SingletonCentre is a singleton that holds the mutable array myQuedHighScores 
    // which holds HighScoreKeeper objects I want to send //

    SingletonCentre *sharedHSData = [SingletonCentre sharedSingleton];
    
    NSMutableArray* sendAllJSONDICT = [[NSMutableArray alloc]init];
    NSLog(@"Found Qued HighScores: %i",[sharedHSData.myQuedHighScores count]);
    
    for (HighScoreKeeper *myHighscoreToSend in sharedHSData.myQuedHighScores ) {
        NSLog(@"name: %@ time: %@ gametime: %i",myHighscoreToSend.name,myHighscoreToSend.gameTime,
          myHighscoreToSend.gameTimeSeconds);
        
        NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                                myHighscoreToSend.name,@"userName",
                                myHighscoreToSend.gameTime,@"userID",
                                [NSNumber numberWithInt:myHighscoreToSend.gameTimeSeconds],@"score",
                                nil];

        [sendAllJSONDICT addObject:params];
        
       
    }    
   NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendAllJSONDICT options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
   
 NSLog(@"jsonData sending string:\n%@", jsonString);  
    
 // ***What do I do now.???? Defiantly where I'm stuck !! **** //
  NSDictionary *paramsit = [NSDictionary dictionaryWithObjectsAndKeys:@{jsonString,nil}];
 
    [httpClient postPath:@"/registar_working_score.php" parameters:paramsit success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"Request Successful, response '%@'", responseStr);
        sharedHSData.queuedItems--;
        // if the HighScore was sent then return YES if not NO //
        sharedHSData.errorUploading=NO;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"OKTOUPDATEHIGHSCORES" object:nil];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
        sharedHSData.errorUploading=YES; 
        [[NSNotificationCenter defaultCenter] postNotificationName:@"SHOWMETHESTATUSE" object:nil];
        
    }];
}

Here's the output:

Code:
2013-10-12 15:46:59.294 UIScrollView-Paging-networked[3567:207] Sending Qued Data
2013-10-12 15:46:59.301 UIScrollView-Paging-networked[3567:207] Found Qued HighScores: 4
2013-10-12 15:46:59.302 UIScrollView-Paging-networked[3567:207] name: UghBugs time: 00:08:01 gametime: 481
2013-10-12 15:46:59.302 UIScrollView-Paging-networked[3567:207] name: 1 UghBugs time: 00:08:02 gametime: 0
2013-10-12 15:46:59.302 UIScrollView-Paging-networked[3567:207] name: 2 UghBugs time: 00:08:03 gametime: 0
2013-10-12 15:46:59.302 UIScrollView-Paging-networked[3567:207] name: 3 UghBugs time: 00:08:32 gametime: 0
2013-10-12 15:46:59.303 UIScrollView-Paging-networked[3567:207] jsonData sending string:
[
  {
    "userName" : "UghBugs",
    "userID" : "00:08:01",
    "score" : 481
  },
  {
    "userName" : "1 UghBugs",
    "userID" : "00:08:02",
    "score" : 0
  },
  {
    "userName" : "2 UghBugs",
    "userID" : "00:08:03",
    "score" : 0
  },
  {
    "userName" : "3 UghBugs",
    "userID" : "00:08:32",
    "score" : 0
  }
]
2013-10-12 15:46:59.304 UIScrollView-Paging-networked[3567:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSDictionary dictionaryWithObjectsAndKeys:]: second object of each pair must be non-nil.  Or, did you forget to nil-terminate your parameter list?'

take this

Code:
 NSMutableArray* sendAllJSONDICT = [[NSMutableArray alloc]init];

and make it an NSMutableDictionary then add all your JSON data
 
Solved

Most of the problems were with my php.
So I wrapped the JSON String in another dictionary.

Code:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendAllJSONDICT options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
   // this is the important part. 
 NSDictionary *paramass =[NSDictionary dictionaryWithObject:jsonString forKey:@"jsonarr"];

 // Basically because I want to keep working with AFNetworking. which wanted a dictionary. 


    [httpClient postPath:@"/myphptodealwithHSs.php" parameters:paramass success:^(AFHTTPRequestOperation *operation, id responseObject) {
// stuff happens // 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// deal with errors 
}

then on the PHP side.
Code:
$arr = $_POST['jsonarr'];
$decarr = json_decode($arr,true); // $arr, true
// do some loop to make a long list of values  // 
//  so it can be upload in one Querry // 

$sql = "INSERT INTO HighScore_elements_global(userName, userID, score) VALUES ".implode(',', $values);

Thanks for all your help.. hope this helps someone else!
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.