Certain JSON requests crach on adHoc, but not on debug - iphone

I am using json-framework for communication purposes with certain web service. So far it has served me well. However, this code crashes my adHoc app on the device. The same app in debug mode on the device works ok.
Here is my JSON request(that is where it crashes):
//Make values dictionary
NSMutableDictionary *valuesDictionary;
NSMutableDictionary *valuesDictionary_1;
NSMutableArray *tempArray;
NSMutableArray *values = [[NSMutableArray alloc] init];;
NSEnumerator * enumerator = [self.contactsTempArray objectEnumerator];
id tempObj;
while ( tempObj = [enumerator nextObject] ) {
valuesDictionary = [[NSMutableDictionary alloc] init];
valuesDictionary_1 = [[NSMutableDictionary alloc] init];
tempArray = [[NSMutableArray alloc] init];
//NSString *key = [NSString stringWithFormat:]
if([[tempObj objectForKey:#"Checked"] isEqualToString:#"1"]) {
[valuesDictionary setObject:[NSNumber numberWithInt:[[tempObj objectForKey:#"NotificationContactId"] intValue]] forKey:#"ContactId"];
[valuesDictionary setObject:[NSNumber numberWithBool:true] forKey:#"IsEnabled"];
}
else {
[valuesDictionary setObject:[NSNumber numberWithInt:[[tempObj objectForKey:#"NotificationContactId"] intValue]] forKey:#"ContactId"];
[valuesDictionary setObject:[NSNumber numberWithBool:false] forKey:#"IsEnabled"];
}
[tempArray addObject:valuesDictionary];
[tempArray addObject:valuesDictionary_1];
[values addObject:valuesDictionary];
[valuesDictionary release];
}
//UPDATE NOTIFICATIONS SETTINGS
//JSON POST request
NSArray *keys = [NSArray arrayWithObjects:#"sessionId", #"apiKey", #"deviceToken", #"values", nil];
NSArray *objects = [NSArray arrayWithObjects:appDelegate.sessionId, appDelegate.apiKey, appDelegate.deviceToken, values, nil];
NSDictionary *getAllSensorsDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString *requestString = [NSString stringWithFormat:#"%#", [getAllSensorsDict JSONFragment], nil];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: #"https://xxxxxxxxx"]];
[request setValue:#"application/json;charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: requestData];
//JSON response
NSData *jsonData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
any ideas what am I doing wrong?
Is the JSON request too complex for adHoc?

Connect your iphone to your mac. Then open xcode, open menu, window, organizer. There go to "crash logs" and look the info about the crash....
Or you can even test your app in your iphone (connected to the mac) using the Build and Go button. You will see the crash messages in the console.

Related

Request failed 'JSON'

I have JSON format like below i need to post request to sever but the response from the server is error 500.
{"firstName":"Sharath K", "lastName":"babu",
"moMerchantAddresses":[{"email":"abc#abc.co.in"}]} >
NSMutableArray *objects = [NSMutableArray arrayWithObjects:#"Sharath",#"babu",#"[{\"email\":\"abc#abc.co.in\"}]", nil];
NSMutableArray *keys = [NSMutableArray arrayWithObjects:#"firstName",#"lastName",#"moMerchantAddresses", nil];
NSMutableDictionary *jsonDict = [NSMutableDictionary dictionaryWithObjects:objects forKeys:keys];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:nil];
NSString *postLength = [NSString stringWithFormat:#"%d",[jsonData length]];
ServiceInterface *service = [[ServiceInterface alloc] init];
service.theDelegate = self;
service.theSuccessMethod = #selector(responseMerchantCreationService:);
service.theFailureMethod = #selector(requestFailedWithError:);
[self addServiceInterfaceToServiceStack:service];
NSString* stringURL = [kBase_URL stringByAppendingString:#"/merchant/create"];
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
[request setTimeoutInterval:30.0f];
NSLog(#"request file :: %#",request);
[service startWithRequest:request];
service = nil;
Please Help me in this
It may helps you .
NSMutableDictionary *emailDict = [[NSMutableDictionary alloc] initWithCapacity:0];
[emailDict setObject:#"abc#abc.co.in" forKey:#"email"];
NSMutableArray *emailArr = [[NSMutableArray alloc] init];
[emailArr addObject:emailDict];
NSMutableDictionary *mainDict = [[NSMutableDictionary alloc] initWithCapacity:0];
[mainDict setObject:#"Sharath" forKey:#"firstName"];
[mainDict setObject:#"babu" forKey:#"lastName"];
[mainDict setObject:emailDict forKey:#"moMerchantAddresses"];
Now change this mainDict to NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mainDict options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:nil];

passing parameters in wcf using iphone

I am passing some parameters to wcf service to get the data, every thing running fine but i am not getting the data. i want to check how the parameters are calling the service and debug it. can any one let me know how to check it.
please find my code below for your reference.
NSArray *propertyNames = [NSArray arrayWithObjects:#"studentID", nil];
NSArray *propertyValues = [NSArray arrayWithObjects:#"E6A83233-7D7F-49AF-B54E-375BBF3E3E59", nil];
NSDictionary *properties = [NSDictionary dictionaryWithObjects:propertyValues forKeys:propertyNames];
// NSMutableDictionary* personObject = [NSMutableDictionary dictionary];
// [personObject setObject:properties forKey:#"person"];
NSMutableArray * arr;
//[arr addObject: personObject];
arr=[[NSMutableArray alloc]initWithObjects:properties, nil];
NSLog(#"%#",arr);
// NSString *jsonString = [personObject JSONRepresentation];
//NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError * error;
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://parentportal.technologyorg.com/parentportal.svc/GetSchoolEvents"]];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
[request setValue:jsonString forHTTPHeaderField:#"json"];
[request setHTTPMethod:#"Post"];
[request setHTTPBody:jsonData2];
NSLog(#"JSON String: %#",jsonString);
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned) {
//...handle the error
NSLog(#"error");
}
else {
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//...do something with the returned value
NSLog(#"RETVAL%#",retVal);
}
let me know if any thing went wrong

Send json to php using ASIFormDataRequest

I'm new in iPhone and I'm trying to convert NSMutable array to json string then send this string to php file using request, and then print it again using respond to NSLog to ensure that it has been send successfully. So I wrote the following code in viewDidLoad
NSString *phpUrl = #"http://dt-works.com/eman/bookMarks.php";
NSMutableArray *arrayKey = [[NSMutableArray alloc] initWithObjects:#"one", #"two", #"three", nil];
NSMutableArray *arrayValue1 = [[NSMutableArray alloc] initWithObjects:#"1", #"2", #"3", nil];
NSMutableArray *arrayValue2 = [[NSMutableArray alloc] initWithObjects:#"11", #"22", #"33", nil];
NSDictionary *theReqDictionary1 = [NSDictionary dictionaryWithObjects:arrayValue1 forKeys:arrayKey];
NSDictionary *theReqDictionary2 = [NSDictionary dictionaryWithObjects:arrayValue2 forKeys:arrayKey];
NSMutableArray *myArray = [NSMutableArray arrayWithObjects:theReqDictionary1,theReqDictionary2, nil];
NSString *jsonString = [myArray JSONRepresentation];
NSLog(#"%#", jsonString);
NSDictionary *questions = nil;
NSURL *link = [NSURL URLWithString:[phpUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link];
[request setPostValue:jsonString forKey:#"jsonString"];
[request setTimeOutSeconds:120];
[request setDelegate:self];
NSError *error = [request2 error];
[request2 startSynchronous];
if (!error) {
NSData *response = [request responseData];
NSString *json = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
questions = [json objectFromJSONString];
NSLog(#"Data: %#", questions);
}
and the code in bookMarks.php is:
$handle = fopen('php://input','r');
$jsonInput = $_POST['jsonString'];
print_r($jsonInput);
but it gives me:
[{"one":"1","two":"2","three":"3"},{"one":"11","two":"22","three":"33"}]
Data: (null)
and I want Data to be as: [{"one":"1","two":"2","three":"3"},{"one":"11","two":"22","three":"33"}]
how to do this??
Try this, instead of posting the JSON string with a key, you need to post it as Data to your script to be read in. Currently in your script you aren't even using $handle for anything...
NSURL *link = [NSURL URLWithString:[phpUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link];
[request appendPostData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request setTimeOutSeconds:120];
[request setDelegate:self];
And your php code..
$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
$decoded = json_decode($jsonInput,true);
print_r($decoded);

IOS - How can I inspect the JSON NSData the SBJson creates?

I am attempting to POST some simple JSON to a RESTful service. I want to form a json string that takes the following form:
{username:"someuser",password:"somepassword"}
My POST keeps failing at the server complaining that POSTed values do not exist. However the same service works fine if I create a JS test implementation. So I'm pretty sure its my SBJson client implementation that is the problem.
NSDictionary *userDict = [[NSDictionary alloc] initWithObjectsAndKeys:
userName,#"username",
password, #"password",
nil];
SBJsonWriter *writer = [[SBJsonWriter alloc]init];
NSData *jsonData = [writer dataWithObject:userDict];
jsonData appears to have size but it attempt to serialize it with SBJson its fails and I get nil.
NSString *test = [writer stringWithObject:jsonData]; // returns nil
I am trying to post the above in a NSMutableURLRequest. Here's my implementation if it helps give context:
-(void)registerUserName:(NSString *)userName andPassword:(NSString *)password{
responseData = nil;
responseData = [NSMutableData data];
NSDictionary *userDict = [[NSDictionary alloc] initWithObjectsAndKeys:
userName,#"username",
password, #"password",
nil];
SBJsonWriter *writer = [[SBJsonWriter alloc]init];
NSData *jsonData = [writer dataWithObject:userDict];
NSString *test = [writer stringWithObject:jsonData]; //always nil
NSURL *url = [[NSURL alloc] initWithString:#"http://localhost/~user/app_web/index.php/user/create"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request addValue:#"form-data" forHTTPHeaderField:#"Content-Disposition"];
[request setHTTPBody:jsonData];
[[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:YES ];
currentRequestType = REGISTER_USER;
NSURLConnection *connection =[[NSURLConnection alloc]initWithRequest:request delegate:self];
Thanks!
update
Using the suggestions below I am now doing this:
NSDictionary *userDict = [[NSDictionary alloc] initWithObjectsAndKeys:
userName,#"username",
password, #"password",
nil];
NSString *jsonString = [userDict JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding];
[request setHTTPBody:jsonData];
[[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:YES ];
currentRequestType = REGISTER_USER;
NSURLConnection *connection =[[NSURLConnection alloc]initWithRequest:request delegate:self];
Unfortunately my posted values are still not found at the server. I think something must be wrong with my NSMutableURLRequest..
I am using CodeIgniter on the backend. The action looks like this:
public function create(){
if($this->input->post('username') && $this->input->post('password')){
$username = $this->input->post('username');
$password = $this->input->post('password');
$this->load->model('User_model','users');
$status = $this->users->add_user($username,$password);
if($status){
echo json_encode(array('success'=>true));
} else{
echo json_encode(array('success'=>false));
}
}
echo json_encode(array('success'=>false)); // when posting I arrive here
}
To serialize the dictionary userDict call the following method.
NSString* jsonString = [userDict JSONRepresentation];
If you want the NSData representation you can use the following method
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8Encoding];
try this:
NSDictionary *userDict = [[NSDictionary alloc] initWithObjectsAndKeys:
userName,#"username",
password, #"password",
nil];
SBJsonWriter *writer = [[SBJsonWriter alloc]init];
NSString *test = [writer stringWithObject:userDict];
don't forget to release them

Iphone sdk, memory leak

im new with objective-c. I have problem with memory leaking when developing iphone app. Leaking utility in Xcode shows that leaking problem with 'combArr'->'results' object. There is my function which parsing json from url and returns NSArray:
- (NSArray *)getListing2:(NSString *)item
from:(int)country {
//sending post request with some params
NSString *post = [#"product=" stringByAppendingString:item];
NSString *countryStr = [NSString stringWithFormat:#"&country=%d", country];
post = [post stringByAppendingString:countryStr];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *url = [prefs objectForKey:#"urlToApi"];
url = [url stringByAppendingString:#"/get-items/"];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
[request release];
//receiving json
NSString *jsonString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
SBJsonParser *json = [[SBJsonParser alloc] init];
NSError *error = nil;
//parsing json to nsdictionary
NSDictionary *results = [[NSDictionary alloc] initWithDictionary:[json objectWithString:jsonString error:&error]];
[json release];
[jsonString release];
//generate array of items
NSMutableArray *listOfItems = [[NSMutableArray alloc] init];
for (int i = 0; i < [[results objectForKey:#"data"] count]; i++) {
[listOfItems addObject:[[results objectForKey:#"data"] objectForKey:[NSString stringWithFormat:#"%d", i]]];
}
//saving items array and count info object into one array
NSArray * returnArr = [[[NSArray arrayWithObjects:listOfItems, [results valueForKey:#"count_info"], nil] retain] autorelease];
[listOfItems release];
[results release];
return returnArr;
}
And i executing this function here:
myApi *itemsApi = [[myApi alloc] init];
NSArray *combArr = [[izdApi getListing2:item from:countryId] retain];
[itemsApi release];
listOfItems = [[combArr objectAtIndex:0] retain];
if([listOfItems count] > 0){
priceArr = [[combArr objectAtIndex:1] retain];
}
else{
totalCount = 0;
}
[combArr release];
Thank you for helping
Every time you allocate memory, you must release it. (alloc, copy, retain).
You are releasing myApi, not itemsApi. Try this...
myApi *itemsApi = [[itemsApi alloc] init];
NSArray *combArr = [[izdApi getListing2:item from:countryId] retain];
[itemsApi release];
listOfItems = [[combArr objectAtIndex:0] retain];
if([listOfItems count] > 0){
priceArr = [[combArr objectAtIndex:1] retain];
}
else{
totalCount = 0;
}
[combArr release];
If you are using Xcode 4, Try turning on ARC. In short, ARC handles the releasing of all memory. A little burden off your shoulders and one less thing for you to worry about.