post method in nsurlconnection in ios - ios

I am new to iOS i need to show particular object for key in textview or picker view using post method response.
coding:
NSString *parameter = [NSString stringWithFormat:#"username=%#",user];
NSData *parameterData = [parameter dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: URL];
NSLog(#"%#", parameterData);
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:parameterData];
NSString *content = [NSString stringWithUTF8String:[parameterData bytes]];
}
[request setHTTPMethod:method];
[request addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if( connection )
{
mutableData = [NSMutableData new];
}
}
delegate method:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseStringWithEncoded = [[NSString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
// NSLog(#"Response from Server : %#", responseStringWithEncoded);
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData: mutableData
options:kNilOptions
error:&error]; //Now we got top level dictionary
// (2)
arrdata =[json objectForKey:#"Branches"];
//(2)
NSLog(#"%#",[arrdata valueForKey:#"id"]);
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[responseStringWithEncoded dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
serverResponse.attributedText = attrStr;
//serverResponse.text = arrdata;
}
I am successfully showed in NSLOG as below :
But in textview it is not updating. How can I fix this?

serverResponse.text = [arrdata valueForKey:#"id"];

Try out the below code:
dispatch_async(dispatch_get_main_queue(),^ {
//Update your UI Component here
serverResponse.attributedText = attrStr;
//or uncomment below line and comment upper line
//serverResponse.text = [arrdata valueForKey:#"id"];
});

All the UI changes must be carried out in Main thread.
Hence probably this may be the issue.
so, at the end of connectionDidFinishLoading wrap textview with GCD main queue like below :
dispatch_async(dispatch_get_main_queue(),^ {
//Update text view
serverResponse.attributedText = attrStr;
});

Related

Objective c - Memory Usage Keeps Increasing - Iphone App

I have a recursive loop using NSTimer that runs every two seconds and calls a function that calls the setupPhpCall function:
There are 3 NSTimers that run and always hits the setupPhpCall function,
could this be where the memory leakage is happening?
-(NSString*)setupPhpCall:(NSString*)requestString :(NSString*)sciptPage{
NSData *myRequestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
// Create your request string with parameter name as defined in PHP file
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: [NSString stringWithFormat: #"http://www.xxxx.co.uk/%#", sciptPage]]];
// set Request Type
[request setHTTPMethod: #"POST"];
// Set content-type
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
// Set Request Body
[request setHTTPBody: myRequestData];
// Now send a request and get Response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&urlResponse error: &error];
// Log Response
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",response);
return response;
}
This is the recursive method thats called using NSTimer:
-(void)recurseForumActivity:(NSTimer *)timer{
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^{
NSString *myRequestString = [NSString stringWithFormat:#"lastDate=%#&threadTitle=%#&threadCountry=%#&threadCategory=%#&threadSubCategory=%#&getData=0",lastDateForumActivity,searchThreadTitle, searchThreadCountry, searchThreadCategory, searchThreadSubCategory];
NSString *response = [self setupPhpCall:myRequestString :#"xxx.php"];
dispatch_async(dispatch_get_main_queue(), ^{
if(response.length > 0 && ![response isEqualToString:#"[]"]){
labelNewForumThreads.text = [NSString stringWithFormat:#"%# new threads...", response];
if(imageviewForumAlert == NULL){
UIImage *image = [UIImage imageNamed:#"alert.png"];
imageviewForumAlert = [UIImageView new];
[viewNav1 addSubview:imageviewForumAlert];
imageviewForumAlert.translatesAutoresizingMaskIntoConstraints = NO;
imageviewForumAlert.image = image;
NSDictionary *viewsDictionary = #{#"imageviewForumAlert":imageviewForumAlert};
NSArray *constraint_H = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-19-[imageviewForumAlert(12)]-19-|"
options:0
metrics:nil
views:viewsDictionary];
NSArray *constraint_V = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-19-[imageviewForumAlert(12)]-19-|"
options:0
metrics:nil
views:viewsDictionary];
[self.view addConstraints:constraint_H];
[self.view addConstraints:constraint_V];
}else{
imageviewForumAlert.hidden = NO;
}
/**NSDictionary *dic = [response JSONValue];
if((NSNull*)dic != [NSNull null]){
labelNewForumThreads.text = [NSString stringWithFormat:#"%d new threads...", dic.count];
}**/
}else{
imageviewForumAlert.hidden = YES;
labelNewForumThreads.text = [NSString stringWithFormat:#"%d new threads...", 0];
}
/**else{
labelNewForumThreads.text = [NSString stringWithFormat:#"%d new threads...", 0];
}**/
});
});
}
EDIT
In the console i get this error after i have left the app to run for more than one hour:
Communications error: <OS_xpc_error: <error: 0x361c0614> { count = 1, contents =
"XPCErrorDescription" => <string: 0x361c086c> { length = 22, contents = "Connection interrupted" }
}>
i have Allocation tool running aswel
this is the screenshot of allocation tool when the app crashes
EDIT
EDIT
I have also noticed when starting Instrument Allocations tool my memory usage rapidly shots up quicker, why is this?

French accents on cell.detailTextLabel in UITableView (Objective-C)

I have a problem I can't deal with.
In my application, I get datas from my Web Service in JSON. It's UTF8-encoded and when I fill an UITableView everything is ok (NSLog return accents like : "\u00e9" but my UITableView shows it like : "é").
But when I set the same data in my detailTextLabel, it doesn't convert "\u00e9" to "é" ...
Tried some tricks with encoding, but nothing convincing.
Parsing methods :
- (NSDictionary*)fetchedData:(NSData *)responseData {
NSError* error;
self.json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
return self.json;
}
-(void)executeParsingWithUrl:(NSURL*)anUrl{
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:anUrl];
NSString *authStr = [NSString stringWithFormat:#"%#:%#",[[NSUserDefaults standardUserDefaults] stringForKey:#"username_ws"], [[NSUserDefaults standardUserDefaults] stringForKey:#"password_ws"]];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [Base64 encode:authData]];
[urlRequest setValue:authValue forHTTPHeaderField:#"Authorization"];
NSError *requestError = NULL;
NSHTTPURLResponse *response = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&requestError];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:responseData waitUntilDone:YES];
}
Recuperation :
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
JsonParsing *getJson = [[JsonParsing alloc] init];
[getJson executeParsingWithUrl: leUrl];
self.duration = [NSString stringWithFormat:#"%#",[[getJson.json objectForKey:#"objects"]valueForKey:#"libel"]];
});
Thanks in advance !
I managed it thanks to other people.
I my cell.detailTextLabel I used this :
cell.detailTextLabel.text = [NSString stringWithCString:[myText cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding];

ASIHTTPRequest + SBJSon iphone

I am working with an application where I have to request a url and I get the response accordingly
I am using ASIHTTPRequest to request the URL
here is my request
-(void)getTips {
if ([CommonFunctions networkConnected]) {
ShowNetworkActivityIndicator();
NSString *strPhp = #"staticpage.php";
NSString *strQuery = [[NSString alloc] initWithString:[NSString stringWithFormat:#"%#%#?static_id=3",GMS_URL,strPhp]];
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:strQuery]];
NSLog(#"tips url %#",request.url);
request.delegate = self;
[request setRequestMethod:#"GET"];
[request startAsynchronous];
}
}
These are my delegate methods
-(void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data {
// NSString *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(#"responseStr %#",responseStr);
SBJsonParser *json = [[SBJsonParser alloc]init];
NSLog(#"json data %#",[json objectWithData:data]);
NSMutableArray *marrData = [[json objectWithData:data] valueForKey:#"responseData"];
if([[marrData valueForKey:#"result"] isEqualToString:#"failed"]){
[CommonFunctions showAlertMessage:[marrData valueForKey:#"error"]];
}
HideNetworkActivityIndicator();
}
Here I get null data no matter whether I pass request methods GET or POST
When I check the same url in browser I get the response and a valid json from online json viewer
What are the possible reason that I am getting null data in the application
Use requestFinished: delegate.. Please try this.
-(void)requestFinished:(ASIHTTPRequest *)request
{
NSLog(#"response %#", [request responseString]);
}

NSXML XML Parsing issue iOS

I know that there are plenty of questions that have been asked and answered and non of them pertain to my problem.
I am posting XML to a server and I get a response back. My problem is getting a specified key back from the response.
I am trying to list all Genders e.g Male, Female and their id's however when parsing the XML into text with NSXML I only get back the Female and ID 2 and I do not get back Male?
I have researched and tried to fix this issue but to no avail.
here is my code:
- (void)getGender {
NSString *soapMessage = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:app=\"http://app.ws.api.bells.wigroup.com/\">"
"<soap:Header/>\n"
"<soap:Body>\n"
"<app:getAllGenders>\n"
"<request>\n"
"<apiCredentials>\n"
"<apiId>IPHONE_APP</apiId>\n"
"<sha1Password>8656cafcd71cbbfe773a0fdb6c422666a80e5b8f</sha1Password>\n"
"</apiCredentials>\n"
"<request>\n"
"</request>\n"
"</request>\n"
"</app:getAllGenders>\n"
"</soap:Body>\n"
"</soap:Envelope>\n"
];
NSLog(#"Message%#",soapMessage);
NSURL *url = [NSURL URLWithString:#"http://qa.wigroup.co:8080/bells/AppWS"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
//[theRequest addValue: #"http://" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Login response XML:%#",str);
// create and init NSXMLParser object
XmlArrayParser *parser = [[XmlArrayParser alloc] initWithData:urlData];
parser.rowElementName = #"return";
parser.elementNames = [NSArray arrayWithObjects:#"response", #"responseCode", #"responseDesc", #"gendersList", nil];
parser.attributeNames = [NSArray arrayWithObjects:#"id", #"gender", nil];
if ([parser.rowElementName isEqualToString:#"responseCode"] && _flag)
{
//read the value here
NSLog(#"flagging");
}
// parsing...
BOOL success = [parser parse];
// test the result
if (success)
{
NSMutableArray *loginAuth = [parser items];
// self.textView.text = [NSString stringWithFormat:
// #"This is an array of dictionaries, one dictionary for each user:\n\n%#",
// [users description]];
// NSDictionary *eventLocation = [NSDictionary dictionaryWithObjectsAndKeys:#"response", nil];
NSDictionary *loginResponse = [loginAuth objectAtIndex:0]; // this retrieves the first user
NSString *userResponse = loginResponse[#"gendersList"]; // this retrieves that user's username in Xcode 4.5 and greater
NSString *userRes = [loginResponse objectForKey:#"id"];
NSString *test = [loginAuth description];
NSLog(#"Returned Code loginResponse %#",loginResponse);
NSLog(#"Returned Code userResponse %# %#",userResponse, userRes);
NSLog(#"Returned Code test %#",test);
NSMutableArray *array=[[NSMutableArray alloc]initWithCapacity:10];
for (NSDictionary *defineXMLData in loginAuth) {
NSNumber * responseCode = [defineXMLData objectForKey:#"responseCode"];
NSArray * responseDEsc = [defineXMLData objectForKey:#"responseDesc"];
NSArray * genderList = [defineXMLData objectForKey:#"gendersList"];
// NSArray * gender = [defineJsonData objectForKey:#"gender"];
NSLog(#"Genders%#", genderList);
[array addObject: responseCode];
[array addObject: responseDEsc];
[array addObject: genderList];
//[array addObject: gender];
// [array addObject: vouchersUser];
}
label.numberOfLines = 2000; // for example
label.lineBreakMode = NSLineBreakByClipping;
NSString *output=[array componentsJoinedByString:#","];
label.text = [NSString stringWithFormat:#"XML Result: %# ",output];
[SVProgressHUD dismiss];
// [[[UIAlertView alloc] initWithTitle:nil
// message:[NSString stringWithFormat:#"No errors - user count : %i", [[parser items] count]]
// delegate:nil
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil] show];
}
else
{
NSLog(#"Error parsing document!");
// [[[UIAlertView alloc] initWithTitle:nil
// message:#"Error parsing document!"
// delegate:nil
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil] show];
}
}
else
{
NSLog(#"theConnection is NULL");
}
NSLog(#"test");
}
And the XML I get back from my nslog:
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:getAllGendersResponse xmlns:ns2="http://app.ws.api.bells.wigroup.com/">
<return>
<responseCode>-1</responseCode>
<responseDesc>Success</responseDesc>
<response>
<responseCode>-1</responseCode>
<responseDesc>Success</responseDesc>
<gendersList>
<gender>Male</gender>
<id>1</id>
</gendersList>
<gendersList>
<gender>Female</gender>
<id>2</id>
</gendersList>
</response>
Is only parsing:
{
gendersList = Female2;
responseCode = "-1";
responseDesc = Success;
}
You have not correctly pointed the problem. Your code parses the whole document, but you keep only the last items (last genderList, last responseCode, last responseDesc). Initialize an array and in your for loop add each dictionary to that array when parsed.

ios parsing json result after http request

am starting to build login form reading from external server via http request i need to parse json result to get user name
- (IBAction)getlogin:(UIButton *)sender {
NSString *rawStrusername = [NSString stringWithFormat:#"username=%#",_username.text];
NSString *rawStrpassword = [NSString stringWithFormat:#"password=%#",_password.text];
NSString *post = [NSString stringWithFormat:#"%#&%#", rawStrusername, rawStrpassword];
// NSString *post = #"rawStrusername&rawStrpassword";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
/* NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]]; */
NSURL *url = [NSURL URLWithString:#"http://www.othaimmarkets.com/my_services_path/user/login.json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
/* [request setValue:postLength forHTTPHeaderField:#"Content-Length"]; */
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
//NSLog(#"responseData: %#", responseData);
}
I get this result:
{"sessid":"g2ev7til6d750ducrkege0cbj2","session_name":"SESS02795057fe9e6b2fc0777bf4057b248f","user":{"uid":"617","name":"mohammed.abdelrasoul#gmail.com","mail":"mohammed.abdelrasoul#gmail.com","mode":"0","sort":"0","threshold":"0","theme":"","signature":"","signature_format":"0","created":"1316602317","access":"1352643854","login":"1352666338","status":"1","timezone":"10800","language":"ar","picture":"","init":"mohammed.abdelrasoul#gmail.com","data":"a:5:{s:18:\"country_iso_code_2\";s:2:\"SA\";s:13:\"timezone_name\";s:11:\"Asia/Riyadh\";s:5:\"block\";a:1:{s:7:\"webform\";a:1:{s:15:\"client-block-88\";i:1;}}s:13:\"form_build_id\";s:37:\"form-3ae73833f08accc7abe5517347ea87eb\";s:7:\"contact\";i:0;}","country_iso_code_2":"SA","timezone_name":"Asia/Riyadh","block":{"webform":{"client-block-88":1}},"form_build_id":"form-3ae73833f08accc7abe5517347ea87eb","contact":0,"roles":{"2":"authenticated user"}}}
Or, formatted for the sake of legibility:
{
"sessid":"g2ev7til6d750ducrkege0cbj2",
"session_name":"SESS02795057fe9e6b2fc0777bf4057b248f",
"user":{
"uid":"617",
"name":"mohammed.abdelrasoul#gmail.com",
"mail":"mohammed.abdelrasoul#gmail.com",
"mode":"0",
"sort":"0",
"threshold":"0",
"theme":"",
"signature":"",
"signature_format":"0",
"created":"1316602317",
"access":"1352643854",
"login":"1352666338",
"status":"1",
"timezone":"10800",
"language":"ar",
"picture":"",
"init":"mohammed.abdelrasoul#gmail.com",
"data":"a:5:{s:18:\"country_iso_code_2\";s:2:\"SA\";s:13:\"timezone_name\";s:11:\"Asia/Riyadh\";s:5:\"block\";a:1:{s:7:\"webform\";a:1:{s:15:\"client-block-88\";i:1;}}s:13:\"form_build_id\";s:37:\"form-3ae73833f08accc7abe5517347ea87eb\";s:7:\"contact\";i:0;}",
"country_iso_code_2":"SA",
"timezone_name":"Asia/Riyadh",
"block":{
"webform":{
"client-block-88":1
}
},
"form_build_id":"form-3ae73833f08accc7abe5517347ea87eb",
"contact":0,
"roles":{
"2":"authenticated user"
}
}
}
how i can get the objects data or parse the result to get user name
any help or examples will be appreciated
You need to use the NSJSONSerialization class method, JSONObjectWithData:options:error: to create an NSDictionary:
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
if (! error) {
NSLog(#"%#",jsonDict);
}else{
NSLog(#"%#",error.localizedDescription);
}
This will get you to the point where you can look at the dictionary, which will be easier to read. It looks like you need to use objectForKey:#"sessid" to get you to user, then objectForKey#"user", then objectForKey:#"name" to get you to the name.
Check out this framework for parsing json. https://github.com/stig/json-framework/
Also check out this answer iPhone/iOS JSON parsing tutorial. You'll find a link to a tutorial you can do to get acquainted with json parsing in ios.
See this answer and some code :
NSMutableData *data; // Contains data received from the URL connection declares in header
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)dataIn
{
// Do it this way because connection doesn't guarantee all the data is in
POLLog(#" Tide View connection");
[data appendData:dataIn];
}
- (void) connectionDidFinishLoading:(NSURLConnection *) conn
{
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *results = [jsonString JSONValue]; // This is a new category added to the NSString by SBJSON
//100 parameters
for (int n=0;n<=100;n++)
{
// Get all the returned results
params[n] = [[results objectForKey:[NSString stringWithFormat:#"param%d",n]] floatValue];
}
To expand upon rdelmar's answer (which I think you should accept), you can use NSJSONSerialization and then navigate the NSDictionary results to extract the userName:
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData
options:0
error:&error];
if (error == nil) {
NSDictionary *userDictionary = [jsonDict objectForKey:#"user"];
NSString *userName = [userDictionary objectForKey:#"name"];
// do what you need with the userName
} else {
NSLog(#"%#",error.localizedDescription);
}
Or if using the latest version of Xcode, you can replace those objectForKey references with the even more concise Modern Objective-C syntax:
NSDictionary *userDictionary = jsonDict[#"user"];
NSString *userName = userDictionary[#"name"];

Resources