How to pase a JSON array in iphone sdk? - iphone

I have a login form where the user can login only with the valid memberID and password. If the user enter correct enamel and password i get a result string contains the user information that the user created in the signup process, if it the password is wrong it shows the status 400 as the result string, the result string is the json array which contains one f the above values, one thing is the if the success login occur it gives the staus 200 along with the user information, my need is to retrieve the status message from the array and i need to validate it within the app, if the login success(status 200) it needs to be redirected to the main page; if it is(status 400) it shows a unsuccessful login message.
my code:
EDit
-(IBAction)_clicksbtnsignIN:(id) sender
{
[_txtmemberId resignFirstResponder];
[_txtpassword resignFirstResponder];
NSString *connectionstring = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://www.google.com"]];
if ([connectionstring length]==0) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"you are not connected to the internet" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *emailString = _txtmemberId.text; // storing the entered email in a string.
// Regular expression to checl the email format.
NSString *emailReg = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailReg];
//[pool drain];
if (_txtmemberId.text.length == 0 || _txtpassword.text.length == 0) {
UIAlertView *alertblnk = [[UIAlertView alloc]initWithTitle:#"ALERT" message:#"Fill the required text fields" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alertblnk show];
[alertblnk release];
}
if (([emailTest evaluateWithObject:emailString] != YES) || [emailString isEqualToString:#""])
{
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Alert" message:#"Invalid Email ID" delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
}
else {
[_spinner startAnimating];
NSString *uname = _txtmemberId.text;
NSString *pwd = _txtpassword.text;
NSString *urlVal = #"http://dev.eltouchapps.net/api/?app=1&type=m1&action=t2&var1=";
NSString *urlVal1 = [urlVal stringByAppendingString:uname];
NSString *urlVal2 = [urlVal1 stringByAppendingString:#"&var2="];
NSString *urlVal3 = [urlVal2 stringByAppendingString:pwd];
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)urlVal3,NULL, (CFStringRef)#"\n" "",kCFStringEncodingUTF8 );
NSURL *url = [NSURL URLWithString:encodedString];
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Message" message:resultString delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
lblresult.text = resultString;
NSString *responseString = [resultString responseString];
NSLog(#"Got Profile: %#", responseString);
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *firstName;
if ([[responseJSON valueForKey:#"Status"] isEqualToString:#"200"]) // if success
{
ParallelReadViewController *detailViewController = [[ParallelReadViewController alloc] initWithNibName:#"ParallelReadViewController" bundle:nil];
//detailViewController.firstString = firstString;
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
// do something
firstName = [responseJSON valueForKey:#"FirstName"];
}
}
}
}
Result string is why i get from the server. I know there is parsing of JSONB array we want , but i didn't know how to done this.
Thanks in advance.

based on assumption of your response , try below code
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSMutableDictionary *responseJSON = (NSMutableDictionary *)[responseString JSONValue];
NSString *firstName;
if ([[responseJSON valueForKey:#"Status"] isEqualToString:#"200"]) // if success
{
// do something
firstName = [responseJSON valueForKey:#"FirstName"];
}
Hope it gives you an idea.

Check out this JSON framework: https://github.com/stig/json-framework/

Related

Want to get my captured video back

I have created a camera using AVFoundation, now i want my video back so i can upload it on my server how can i do that ?
I am using MKNetworkKit for upload video on server.
I am getting output like this:
file://localhost/private/var/mobile/Applications/4B2E02E5-3EE2-493E-8ECF-4B1DA29B9387/tmp/output.mov
Guys I have figured out it by some help here is code for that.
- (void) captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)anOutputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error
{
videodata = [NSData dataWithContentsOfURL:outputFileURL];
//NSLog(#"output file url is :%#",anOutputFileURL);
NSLog(#"output video data size is:%d", videodata.length);
if ([[self delegate] respondsToSelector:#selector(recorder:recordingDidFinishToOutputFileURL:error:)]) {
[[self delegate] recorder:self recordingDidFinishToOutputFileURL:anOutputFileURL error:error];
}
//NSLog(#"captureOutput is: %#",captureOutput);
// NSLog(#"anOutputFileURL is: %#",anOutputFileURL);
//videoPath = [NSString stringWithContentsOfURL:anOutputFileURL encoding:NSUTF8StringEncoding error:nil];
//videoPath = [anOutputFileURL absoluteString];
//videoURL = anOutputFileURL;
// videodata = captureOutput;
// NSLog(#"video path is: %#",videodata);
UIAlertView *message = [[UIAlertView alloc] initWithTitle:nil
message:#"Do you want to upload this content to the yes stream network ?"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Yes",#"No",nil];
[message show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Yes"])
{
NSLog(#"Yes was selected.");
self.flUploadEngine = [[fileUploadEngine alloc] initWithHostName:#"manektech.net" customHeaderFields:nil];
NSMutableDictionary *postParams = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"testApp", #"appID",
nil];
self.flOperation = [self.flUploadEngine postDataToServer:postParams path:#"/dilipvideotest/savefile.php"];
[self.flOperation addData:videodata forKey:#"uploadfile" mimeType:#"video/mov" fileName:#"output.mov" ];
[self.flOperation onCompletion:^(MKNetworkOperation *operation) {
NSLog(#"response string is : %#", [operation responseString]);
/*
This is where you handle a successful 200 response
*/
}
onError:^(NSError *error) {
NSLog(#"error : %#", error);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}];
[self.flUploadEngine enqueueOperation:self.flOperation ];
}
else if([title isEqualToString:#"No"])
{
NSLog(#"No was selected.");
//[self readMovie:outputFileURL];
}
}

request send get error: [CFString release]: message sent to deallocated instance 0x6a83e00

I want to check the app version from apple so I send request like below
- (void)connectToCheckVersion{
NSString *url = #"http://itunes.apple.com/lookup?id=466424846";
TTURLRequest *_request = [TTURLRequest requestWithURL:url delegate:self];
_request.httpMethod = #"GET";
_request.cachePolicy = TTURLRequestCachePolicyNone;
_request.shouldHandleCookies = NO;
TTURLJSONResponse* response = [[TTURLJSONResponse alloc] init];
_request.response = response;
TT_RELEASE_SAFELY(response);
[_request send];
}
- (void)requestDidFinishLoad:(TTURLRequest*)request {
TTURLJSONResponse* response = request.response;
NSDictionary* json = response.rootObject;
NSArray *results = [json objectForKey:#"results"];
NSString *version;
for (NSDictionary *rawResult in results) {
version = [rawResult objectForKey:#"version"];
}
NSString *currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleShortVersionString"];
if (version != nil && currentVersion != nil && ![version isEqualToString:currentVersion]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"info"
message:#"newer version"
delegate:self
cancelButtonTitle:#"ok"
otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
}
and after [_request send]; will get [CFString release]: message sent to deallocated instance 0x6a83e00. I checked all Strings in this method seems they are ok, and I can still get correct response from remote.
If I comment out this connectToCheckVersion method then no any problem.
Any diea?
I think that you should retain the _request variable and save it as a member.
Because it will autorelease after the function is returned.
You have to release it after the request is successed or failed.
Thank you.

regarding potential leak

am getting the potential leak in the following code.(returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];)pls help me to find out.
+ (NSString *) getResponseFromServer:(NSString *) url
{
NSString *URLString1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.google.com"]];
if(URLString1 == NULL)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Info" message:#"You must be connected to the Internet to use this app. Wireless , 3G and EDGE are supported" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
alert.delegate = self;
[alert show];
[alert release];
return #"NO" ;
}
else
{
//CFStringRef escapeChars = (CFStringRef) #":/?#[]#!$&’()*+,;=";
// url = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)url, NULL, escapeChars, kCFStringEncodingUTF8);
url = [url stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
//[self alert:escapedUrlString];
url=[url stringByReplacingOccurrencesOfString:#"%2526" withString:#"%26"];
//NSLog(#"url 2 = %# ",url);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
NSLog(#"******Loading URL = %#",[NSURL URLWithString:url]);
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = #"";
if(returnData)
{
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; //Potential leak here...
// NSRange range = [str rangeOfString:supplierSearchText.text options:NSCaseInsensitiveSearch];
//NSLog(#"Searching = %d, %#, %#, %d", i, str, supplierSearchText.text, range.location);
//if(range.location == 0)
int num = [url rangeOfString:#"iphone_logout.php" options:NSCaseInsensitiveSearch].location;
NSLog(#">>>>>>>>> NUmber = %d", num);
if(isUserLoggedIn > 0 && global_Timer != nil && num > 1000)
{
if(((int)([url rangeOfString:#"iphone_user.php" options:NSCaseInsensitiveSearch].location) < 1000) ||
((int)([url rangeOfString:#"company_name.php" options:NSCaseInsensitiveSearch].location) < 1000) ||
((int)([url rangeOfString:#"company_search.php" options:NSCaseInsensitiveSearch].location) < 1000) ||
((int)([url rangeOfString:#"view_web.php" options:NSCaseInsensitiveSearch].location) < 1000))
{
[global_Timer invalidate];
NSLog(#">>>>>>>> Timer invalidating >>>>>>>>>>>>>>, %d, %d, %d, %d", ((int)([url rangeOfString:#"iphone_user.php" options:NSCaseInsensitiveSearch].location) > -1) , ((int)([url rangeOfString:#"company_name.php" options:NSCaseInsensitiveSearch].location) > -1) , ((int)([url rangeOfString:#"company_search.php" options:NSCaseInsensitiveSearch].location) > -1), ((int)([url rangeOfString:#"view_web.php" options:NSCaseInsensitiveSearch].location) > -1) );
global_Timer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)300.0 target:global_SupplierToolsViewController selector:#selector(pressButton_Logout) userInfo:nil repeats:NO];
}
else {
NSLog(#"No matches found!, %d", (int)([url rangeOfString:#"iphone_user.php" options:NSCaseInsensitiveSearch].location));
}
}
}
else //if(!networkFlag)
{
//networkFlag = YES;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Network connection failed! Try again later!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return #"NO";
}
//[url release];
[request release];
return returnString;
}
}
You could add autorelease to the creation of the string.
In general, any time you use alloc you need to either use autorelease or else use release.
You have a path that returns before releasing the request.
else //if(!networkFlag)
{
//networkFlag = YES;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Network connection failed! Try again later!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return #"NO";
}
//[url release];
[request release];
You are alloc-ing returnString without a matching release.
Try having an autoreleased string, like so:
returnString = [NSString stringWithData:returnData encoding:NSUTF8StringEncoding];

Sending Email in background in iphone sdk with body

I am developing on app in that i want to send email at the back ground.
for that i used the "SKPSMTP" library but when i got the mail it is without body so can any one tell me where i m wrong in my code.
following is the code on button click..
- (void)sendMessageInBack:(id)anObject
{
if(![self validateEmail:txt_email.text])
{
if([txt_email.text isEqualToString:#""] )
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Mandatory field" message:#"Please fill complete email" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
if(self.interfaceOrientation==UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation==UIInterfaceOrientationLandscapeRight )
{
if(rotate)
[btn_Send setImage:[UIImage imageNamed:#"send_button.png"] forState:UIControlStateNormal];
}
else if(self.interfaceOrientation==UIInterfaceOrientationPortrait || self.interfaceOrientation==UIInterfaceOrientationPortraitUpsideDown )
{
if(rotate)
[btn_Send setImage:[UIImage imageNamed:#"send button1.png"] forState:UIControlStateNormal];
}
NSLog(#"Start Sending");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"RequestReview.txt"];
NSData *dataObj = [NSData dataWithContentsOfFile:writableDBPath];
//NSString *mailid;
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
testMsg.fromEmail =#"spymekdemo#gmail.com";
testMsg.toEmail = #"priyanka.chinchmalatpure#gmail.com";// txtEmail.text;
testMsg.relayHost = #"smtp.gmail.com";
testMsg.requiresAuth = YES;
testMsg.login = #"spymekdemo#gmail.com";
testMsg.pass =#"spymek123";
testMsg.subject =#"Sbject"; //[NSString stringWithFormat:#"Reply to Review From %#", txtName.text];
testMsg.wantsSecure = YES; // smtp.gmail.com doesn't work without TLS!
// Only do this for self-signed certs!
testMsg.validateSSLChain = NO;
testMsg.delegate = self;
NSString *deviceIdentifier=[NSString stringWithFormat:#"%#",[[UIDevice currentDevice]uniqueIdentifier]];//[NSString stringWithFormat:#"%#",deviceToken.uniqueIdentifier];
NSLog(#"%#",deviceIdentifier);
//NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
// [NSString stringWithFormat:#"Request Review\n\nDevice Identifier=%#\nProduct Name=%#\nProduct Download URL=%#\nUser Name=%#\nEmail=%#\nPromo Code=%#\nDescription Of Product=%#\n\n\n", deviceIdentifier, txtProduct.text,txtDownloadURL.text, txtName.text,txtEmail.text,txtPromocode.text, txtDescription.text]
// ,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/html",kSKPSMTPPartContentTypeKey,
[NSString stringWithFormat:#"<h2>Request Review</h2><br/><br/><b>Thank you for giving us your review</b> <br/>Device Identifier=%#<br/>Product Name=<br/>Product Download URL=<br/>User Name=<br/>Email=<br/>Promo Code=<br/>Description Of Product=<br/><br/><br/>", deviceIdentifier]
,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
// [NSString stringWithFormat:#"<h3>Review App</h3> <br/> <br/><b>Name=%#<b><br/> <br/>,\n<u>Email=%#</u><br/> <br/>,\nPassword=%#,<br/><br/> <b>\nComments=%#\n\n</b><br/>",txtName.text,txtMailId.text, txtPassword.text, txtComment.text],kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
// #"<html><body><h1>Review App</h1> <br/> <b>Some text to include in body</b></body></html>"
NSDictionary *vcfPart = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:#"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"%#.txt\"",txt_name.text],kSKPSMTPPartContentTypeKey,
[NSString stringWithFormat:#"attachment;\r\n\tfilename=\"%#.txt\"",txt_name.text],kSKPSMTPPartContentDispositionKey,[dataObj encodeBase64ForData],kSKPSMTPPartMessageKey,#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArray arrayWithObjects:plainPart,vcfPart, nil]; //vcfPart
[testMsg send];
}
}
rotate=YES;
}
- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{
[message release];
//open an alert with just an OK button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Unable to send email"
delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
//[self ClearFile];
//UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Request Review" message:#"Review Posting failed.. Try Again Later.." delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Done",nil];
}
- (void)messageSent:(SKPSMTPMessage *)message
{
[message release];
NSLog(#"delegate - message sent");
}

UIAlert View-for yes/no condition

my app needs alert msg and if yes button pressed then one more alert msg and then i have to called a method.This is my code:
-(IBAction)resetPressed:(id)sender
{
NSString *title= [NSString stringWithFormat:#"Warning"];
NSString *message = [NSString stringWithFormat:#"Are you sure you want to Reset"];
NSString *ok = [NSString stringWithFormat:#"No"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:ok otherButtonTitles:#"Yes",nil];
[alert show];
[alert release];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (alertView.tag ==1)
{
NSString *title= [NSString stringWithFormat:#"Warning"];
NSString *message = [NSString stringWithFormat:#"Are you sure you want to Reset"];
NSString *ok = [NSString stringWithFormat:#"No"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:ok otherButtonTitles:#"Yes",nil];
alert.tag =2;
[alert show];
[alert release];
}
else if(alertView.tag ==2)
{
[self resetArray];
}
}
Thanks.
I'm not sure what your goal is but a few things look wrong to me anyways:
First of all you should create your strings this way:
NSString *title= #"Warning";
There's no need to use stringWithFormat in your case.
Then, it doesn't seem you properly set the first UIAlert's tag to 1, and the default value for tags is 0 so I guess the if statements in didDismissWithButtonIndex are never true.
Also, you should check which button was pressed using buttonIndex, otherwise you are going to show both alert and call [self resetArray] whichever button is pressed by the user.
Hope that helps.
In your code, you create the first alert, but never actually set the tag on it. You should do:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:ok otherButtonTitles:#"Yes",nil];
alert.tag = 1; //Or 2, or something.
[alert show];
[alert release];
Then the code in your delegate method will run.
Please define two separate UIAlertView in .h file
#interface XYZViewController:UIViewController
{
UIAlertView *firstAlertView;
UIAlertView *secondAlertView;
}
Now in your .m file modify as below:
-(IBAction)resetPressed:(id)sender
{
NSString *title= [NSString stringWithFormat:#"Warning"];
NSString *message = [NSString stringWithFormat:#"Are you sure you want to Reset"];
NSString *ok = [NSString stringWithFormat:#"No"];
if(firstAlertView == nil)
{
firstAlertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:ok otherButtonTitles:#"Yes",nil];
}
[firstAlertView show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (alertView == firstAlertView)
{
NSString *title= [NSString stringWithFormat:#"Warning"];
NSString *message = [NSString stringWithFormat:#"Are you sure you want to Reset"];
NSString *ok = [NSString stringWithFormat:#"No"];
if(secondAlertView == nil)
{
secondAlertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:ok otherButtonTitles:#"Yes",nil];
}
[secondAlertView show];
}
else if(alertView == secondAlertView)
{
[self resetArray];
}
}
and in dealloc method please release the allocated UIAlertviews.
Hope i am clear to you.
Thanks,
Jim.