Response in alert view - ios

I am new to IOS i want to display response from post in alert view.in nslog i showed response. i need when i clicked button alert view can display my response.
coding:
-(void) sendDataToServer : (NSString *) method params:(NSString *)str{
NSData *postData = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[str length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URL]];
NSLog(#"%#",str);
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection ){
mutableData = [[NSMutableData alloc]init];
}
}
alerview:
- (IBAction)butt1:(id)sender {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Value"
message:#"%#"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"ok", nil];
[self sendDataToServer :#"POST" params:str];
[alert show];
}
post method delegates:
here i get response in json111 that i showed in nslog successfully but in alert view i failed
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mutableData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
return;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError* error111;
json111 = [NSJSONSerialization JSONObjectWithData: mutableData
options:kNilOptions
error:&error111];
NSLog(#"%#",json111);
}
[![emptyvalue in alertview][1]][1]

change this into
updated answer
#interface myViewController : UIViewController <UIAlertViewDelegate>
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError* error111;
json111 = [NSJSONSerialization JSONObjectWithData: mutableData
options:kNilOptions
error:&error111];
NSLog(#"%#",json111);
NSArray *temp = [ json111 objectForKey:#"Currencies"];
// you can directly fetch like
NSDictionary *fetchDict = [temp objectAtIndex:0];
NSDictionary *fetchUnit = [temp objectAtIndex:1];
// finally you can fetch like
NSString * total = [fetchDict objectForKey:#"total"];
NSString * one_unit = [fetchUnit objectForKey:#"one_unit"];
//updated
NSString *final = [NSString stringWithFormat:#"%# , %#", total,one_unit];
// in here you can assign the value to Alert
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Value"
message:final
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"ok", nil];
alert.tag = 100;
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 100)
{
if (buttonIndex == 0)
{
// ok button pressed
//[self sendDataToServer :#"POST" params:str];
}else
{
// cancel button pressed
}
}

You should know the basics of NSString, refer here.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Value"
message:[NSString stringWithFormat:#"%#", str]
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"ok", nil];

You can save your response in an NSString and then pass this string in the message field of your alert view.
However, as of iOS 8,
UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead

Change your Alert View as following :
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Value"
message:[NSString stringWithFormat:#"Response Message : %#",str]
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"ok", nil];
This will display your response message instead %#..
If you want to send Data to Server on Click on alertView, you need to write code in alertView Delegate clickedButtonAtIndex
Hope it helps..

Related

can you give me this code in objective c?

hi i am giving reference link of stack over flow
How to update Google Maps marker position in swift/iOS
You can try the online swift to objective c converters. Like
http://objc2swift.me
These converts are used to convert objective c to Swift. I know you want to convert Swift to objective C. But I think you can learn some think to here. Just write the code. Swift is very similar to objective c.Only difference in syntax. You can understand very easily.
*Stack Overflow not for Writing Codes. If you have any Problem in codes. We will help you.
Here is the code, Create a button, add selector to that button. Hope you will set your google map.
NSMutableData *webData;
#property NSURLConnection *connection;
-(void) getResult //call this in button selector
{
marker=nil; //create a GMSMarker globally.
[self.mapView clear];
NSString *strUrl = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%#&type=atm&sensor=true&name=%#&key=%#",latitude,longitude,_radius.text,_searchTxt.text,googleAPI_Key ];
[self addMarkerDataUrl:strUrl];
}
-(void)addMarkerDataUrl:(NSString *)urlString
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString* urlTextEscaped = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlTextEscaped]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
[request setHTTPMethod: #"GET"];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
if(self.connection)
{
webData = [[NSMutableData alloc]init];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (webData)
{
[self gettingData:webData ];
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
webData=nil;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#" response %d",kCFURLErrorNotConnectedToInternet);
if ([error code] == kCFURLErrorNotConnectedToInternet)
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:#"No Connection Error"
forKey:NSLocalizedDescriptionKey];
NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:userInfo];
NSLog(#"error %#",noConnectionError);
[self handleError:noConnectionError];
}
else
{
[self handleError:error];
}
self.connection = nil;
[self errorInConnection];
}
- (void)handleError:(NSError *)error
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"SUBCOMMUNE" message:#"Timed Out" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
-(void)errorInConnection
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Try again after some time" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
- (void) gettingData:(NSData *)data
{
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray* places = [json objectForKey:#"results"];
NSLog(#"Google Data: %#", places);
tempArray = [[NSMutableArray alloc]init];
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if([[NSString stringWithFormat:#"%#",[allDataDictionary objectForKey:#"status"]]isEqualToString:#"OK"])
{
collectionArray =[[NSMutableArray alloc]init];
locArray = [[NSMutableArray alloc]init];
NSMutableArray *legsArray = [[NSMutableArray alloc] initWithArray:allDataDictionary[#"results"]];
for (int i=0; i< [legsArray count]; i++)
{
[collectionArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:legsArray[i][#"icon"],#"icon", legsArray[i][#"name"],#"name",legsArray [i][#"vicinity"],#"vicinity",legsArray[i][#"id"],#"id",nil]];
[locArray addObject:legsArray[i][#"geometry"][#"location"]];
[tempArray addObject:legsArray[i][#"vicinity"]];
}
NSLog(#"CollectionArray =%#",collectionArray);
NSLog(#"LocationArray =%lu",(unsigned long)locArray.count);
[self addMarkers];
}
else
{
NSString *msg=[allDataDictionary objectForKey:#"error_message"];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Error !\n Check Radius or ATM Name" message:msg delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
-(void)addMarkers
{
for(int i=0;i<locArray.count;i++)
{
starting = [NSMutableDictionary dictionaryWithObjectsAndKeys:locArray[i][#"lat"],#"lat",locArray[i][#"lng"],#"lng", nil];
name = [NSMutableDictionary dictionaryWithObjectsAndKeys:collectionArray[i][#"name"],#"name",nil];
CLLocationCoordinate2D position = CLLocationCoordinate2DMake([[starting objectForKey:#"lat"] doubleValue] , [[starting objectForKey:#"lng"] doubleValue]);
marker1 = [GMSMarker markerWithPosition:position];
GMSCameraUpdate *updatedCamera=[GMSCameraUpdate setTarget:CLLocationCoordinate2DMake(latitude, longitude) zoom:15];
[self.mapView animateWithCameraUpdate:updatedCamera];
marker1.title = [name objectForKey:#"name"];
[marker1 setIcon:[UIImage imageNamed:#"Map Pin-48.png"]];
marker1.appearAnimation = YES;
marker1.map = self.mapView;
}
}

How to resolve error:the operation couldn’t be completed. (cocoa error 3840.) json iOS?

I wrote the GET method code to retrieve the details from server(json format).But I am getting the error (the operation could not be completed).
can anyone please provide me some information regarding this?
My code:
-(void)getResponseWithOutBodywithMethod:(NSString*)method
{
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:method];
//[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// [request setTimeoutInterval:20.0];
NSURLConnection *conn=[[NSURLConnection alloc]initWithRequest:request delegate:self];
if (conn)
{
receivedData = [[NSMutableData alloc] init] ;
}
}
#pragma mark NSURLConnection delegate methods
- (void) connection:(NSURLConnection *)connection didReceiveResponse: (NSURLResponse *)response{
/* This method is called when the server has determined that it has
enough information to create the NSURLResponse. It can be called
multiple times, for example in the case of a redirect, so each time
we reset the data. */
[receivedData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData: ( NSData *)data{
[receivedData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:( NSError *)error{
completion(nil, error);
NSLog(#"%#",[error localizedDescription]);
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection{
if (receivedData != nil) {
NSError *jsonParsingError = nil;
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:receivedData
options:kNilOptions error:&jsonParsingError];
NSString* str = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"error %#",jsonParsingError.localizedDescription);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"ER" message:str delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertView show];
if (dict == nil && [dict count]==0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:jsonParsingError.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertView show];
completion(nil, jsonParsingError);
}
else {
completion(dict, nil);
}
}
else {
completion(nil, [NSError errorWithDomain:#"http" code:-1 userInfo:nil]); //todo proper error
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Failed to get data." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertView show];
}
}
Well I would think your Json is the problem.
If your server is responding:
Something=somethingelse
That's not the proper format. You would need to Json encode it so it looks like:
[{"key":"value", "key":"value"}]

Priority execution of methods i iOS

I'm developing an application that should login to a remote service in the first view controller I create a UI to insert username and password.
When I press on the button login I make the following check:
I check if the field aren't empty with a simple if
From my button starts a segue to the internal view controller, before it shows me the internal view controller I added a method that should check if the user can login or not. In this method I call an external class in which I do the connection to the server to authenticate the user
The method to call the external class is the follow:
- (BOOL)loginSuccessWith:(NSString*)userName and:(NSString*)password {
ConnectionHandler *connectionHandler = [[ConnectionHandler alloc]init];
if ([connectionHandler startConnectionToServer:#"serverAddress" andUsername:userName withPassword:password andInstallationId:[[NSUserDefaults standardUserDefaults] objectForKey:#"instId"]]) {
return YES;
} else {
return NO;
}
}
As you can see if the method return YES or NO if the user can be logged or not.
In the ConnectionHandler class I wrote the following code:
#import "ConnectionHandler.h"
#interface ConnectionHandler() {
BOOL authenticated;
}
#end
#implementation ConnectionHandler
- (BOOL)startConnectionToServer:(NSString *)address andUsername:(NSString *)username withPassword:(NSString *)password andInstallationId:(NSString*) installationId {
if (![self sendRequestToURL:address withMethod:#"POST" withUsername:username withPassword:password andInstallationId: installationId]) {
NSLog(#"Impossibile connettersi");
return NO;
} else {
if (authenticated) {
return YES;
} else {
return NO;
}
}
}
- (id)sendRequestToURL:(NSString *)url withMethod:(NSString *)method withUsername:(NSString*)username withPassword:(NSString*)password andInstallationId:(NSString*)installationId {
NSURL *finalURL = [[NSURL alloc]init];
if ([method isEqualToString:#"POST"]) {
finalURL = [NSURL URLWithString:url];
} else {
NSLog(#"Metodo no previsto");
}
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#&installationId=%#", username, password, installationId];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)postData.length];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:finalURL];
[request setHTTPMethod:method];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
[connection start];
}
return connection;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
self.responseData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Parsing della risposta dal server parlare con Giancarlo per vedere che tipo di risposta ottengo
NSDictionary *json;
NSError *err;
json = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&err];
if (err) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"AT Brain" message:#"Impossibile satbilire una connessione con il server" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
} else {
NSString *error_code = [NSString stringWithFormat:#"%#", [json objectForKey:#"error_code"]];
int success = [[json objectForKey:#"success"] intValue];
NSString *error_desc = [NSString stringWithFormat:#"%#", [json objectForKey:#"error_desc"]];
if ([self autenthicationOkWithErrorCode:error_code withSuccess:success andErrorDesc:error_desc]) {
authenticated = YES;
} else {
authenticated = NO;
}
}
}
- (BOOL)autenthicationOkWithErrorCode:(NSString*)error_code withSuccess:(int)success andErrorDesc:(NSString*)error_desc {
int errCode = [error_code intValue];
if (success == 1) {
return YES;
} else if (success == 0) {
if (errCode == 2) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"AT Brain" message:#"Controlla di aver inserito username, password e di avere un installationId" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
return NO;
}
if (errCode == 3) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"AT Brain" message:#"Credenziali non valide, inserisci username e password corrette" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
return NO;
}
if (errCode == 4) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"AT Brain" message:#"Utente non autorizzato ad accedere al servizio" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
return NO;
}
if (errCode == 5) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"AT Brain" message:#"L'utenza a cui stai cercando di accedere è già associata ad un utente diverso" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
return NO;
}
if (errCode == 6) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"AT Brain" message:#"Installation ID errato" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
return NO;
}
}
return NO;
}
I can connect to the server without problem, but before the - (void)connectionDidFinishLoading:(NSURLConnection *)connection is called it execute all the code in the - (BOOL)startConnectionToServer:(NSString *)address andUsername:(NSString *)username withPassword:(NSString *)password andInstallationId:(NSString*) installationId and it returns NO so the segue in the login view controller doesn't work because the method -(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender returns NO.
So my problem is how to wait the execution of the method - (void)connectionDidFinishLoading:(NSURLConnection *)connection is done before execute the else section in method - (BOOL)startConnectionToServer:(NSString *)address andUsername:(NSString *)username withPassword:(NSString *)password andInstallationId:(NSString*) installationId?
I hope you understand my issue and I hope you will help me to fix it, thank you
NSURLConnection is asynchronous. You kick it off and it immediately returns. You get callbacks (such as connectionDidFinishLoading) when it completes. That's the point at which you can check for success and move onto the next step.
I assume that loginSuccessWith:and: is called on the main thread (this is a very strange name for a method; you probably meant loginWithUsername:password:). So it can't block waiting for a network request that may take a very long time to complete. You'd hang the entire UI.
The URL Loading System Programming Guide has a great deal of information on how to design this. Look first at NSURLSession, and if it doesn't meet your needs, then use the lower-level NSURLConnection. With NSURLSession, you can pass completion blocks that will run whenever the operation completes.

I have integrated google plus in my IOS App , Now how can i get profile detail of logged in user?

I have integrated google plus in my ios app ,I am able to get access token.I have used authentication flow to integrate google plus.So now after getting access token how can i get user profile details like username, email id, profile pic etc?
My code to get access token is as below:
-(IBAction)btnGooglePlusClicked:(UIButton *)sender
{
IBwebView.hidden = FALSE;
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%#&redirect_uri=%#&scope=%#&data-requestvisibleactions=%#",GOOGLE_PLUS_CLIENT_ID,GOOGLE_PLUS_CALL_BACK_URL,GOOGLE_PLUS_SCOPE,GOOGLE_PLUS_VISIBLE_ACTIONS];
[IBwebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
// [indicator startAnimating];
if ([[[request URL] host] isEqualToString:#"localhost"]) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"code"]) {
verifier = [keyValue objectAtIndex:1];
NSLog(#"verifier %#",verifier);
break;
}
}
if (verifier) {
NSString *data = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=authorization_code", verifier,GOOGLE_PLUS_CLIENT_ID,GOOGLE_PLUS_CLIENT_SECRET,GOOGLE_PLUS_CALL_BACK_URL];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [[NSMutableData alloc] init];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
NSLog(#"verifier %#",receivedData);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"%#", error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *response = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
SBJsonParser *jResponse = [[SBJsonParser alloc]init];
NSDictionary *tokenData = [jResponse objectWithString:response];
// WebServiceSocket *dconnection = [[WebServiceSocket alloc] init];
// dconnection.delegate = self;
NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#", [tokenData objectForKey:#"refresh_token"], self.isLogin];
// NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#",[tokenData accessToken.secret,self.isLogin];
// [dconnection fetch:1 withPostdata:pdata withGetData:#"" isSilent:NO];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Google Access TOken"
message:pdata
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
I feel the the method you are using will not help to get the profile detail.
I suggest to use the proper method which ensures the best results.
Please check this out : https://developers.google.com/+/mobile/ios/
This will surely help you to get required outcome.

How to show loading view controller in my webservices

I want to show a loading view controller or activity indicator view when I call my loginUserintoserver method but while debugging I found the view becomes inactive at this line.
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
For sometime till I get the response. I have tried showing activity indicators but did not succeed. Please any guidelines to resolve this. Thanks in advance.
-(void) loginUserintoserver
{
NSString *str_validateURL = #"callogin";
// em,password,devicereg,devicetype,flag = ("e" or "m")
NSString *str_completeURL = [NSString stringWithFormat:#"%#%#", str_global_domain, str_validateURL];
NSURL *url = [NSURL URLWithString:str_completeURL];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
str_global_UserPhone = [NSString stringWithFormat:#"%#%#",signupCountryCodeTextField.text,signupMobileTextField.text];
NSString *postData = [NSString stringWithFormat:#"em=%#&password=%#&devicereg=%#&devicetype=%#&flag=%#", loginEmailTextField.text, loginPasswordTextField.text, str_global_DeviceRegID, #"1", [NSString stringWithFormat:#"%#", emailphoneFlag]];
NSLog(#"==============%#",postData);
NSString *length = [NSString stringWithFormat:#"%d", [postData length]];
[theRequest setValue:length forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding]];
// here the view becomes inactive and takes time to get response from server
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
NSLog(#"response data is %#", responseData);
if (responseData == nil)
{
NSLog(#"No data from server");
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"No data downloaded from server!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alertView show];
}
else
{
NSLog(#"response data is %#", responseData);
NSString *returnString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"returnString....%#",returnString);
NSDictionary *response_dic = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];
NSString *msg;
msg = [response_dic objectForKey:#"Result"];
NSDictionary *loginDict=[[NSDictionary alloc]init];
loginDict=[response_dic objectForKey:#"Result"];
NSLog(#"msg is : %# ",[response_dic objectForKey:#"Result"]);
if ([[[response_dic objectForKey:#"Result"] objectForKey:#"ErrorCode"] isEqualToString:#"0"])
{
// success
NSLog(#"Successfull Login!!!!!");
NSString *UserId=[loginDict objectForKey:#"userid"];
[[NSUserDefaults standardUserDefaults] setValue:UserId forKey:#"LoginId"];
[self initRevealViewController];
} else if ([[[response_dic objectForKey:#"Result"] objectForKey:#"ErrorCode"] isEqualToString:#"1"]){
NSLog(#"Invalid Password!");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message: #"ReEnter Password" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}else if ([[[response_dic objectForKey:#"Result"] objectForKey:#"ErrorCode"] isEqualToString:#"3"]){
NSLog(#"Invalid input parameters!");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message: #"Email address or Mobile number, Password, devicereg, devicetype, flag are Mandatory" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}else if ([[[response_dic objectForKey:#"Result"] objectForKey:#"ErrorCode"] isEqualToString:#"6"]){
NSLog(#"Invalid input parameters!");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message: #"User Registered but not activated" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
}
You have to used this: MBProgressHUD
Import framwork from above link and do some stuff like:
.h file:
#import "MBProgressHUD.h"
MBProgressHUD *HUD;
.m file do this :
HUD = [[MBProgressHUD alloc] initWithView:self.view];
[self.view addSubview:HUD];
[HUD show:YES];
// call your webservice here
[HUD hide:YES];
May be it will help.
Happy coding...:)
Mak ,
I use MBProgressHUD all my project . You can use also .Really MBProgressHUD is suitable , lightweight.
Showing indicator :
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
hiding :
[MBProgressHUD hideHUDForView:self.view animated:YES];
Most of the answers are partial which do not point out the main issue in your code.
Synchronous request on main thread will block it, thus you cannot show any UI updates like activity indicator while the sync request is in progress. Instead make asynchronous request (or make request in background using GCD) and use UIActivityIndicatorView or any other open source available for this.
Follow this Q&A to learn how to make asyn request using GCD: NSURLConnection and grand central dispatch
You can create and add an activity indicator to the view. Present and start showing activity when request is initiated and stop the activity when request completes downloading.
Hope that helps!
https://github.com/jdg/MBProgressHUD
Download the project for MBProgressHUD , and copy MBProgressHUD.h & .m classes in to your project, Now by simply creating an instance of MBProgressHUD and using the available methods by MBProgressHUD you can show loading view on to your web services
HUD = [[MBProgressHUD alloc] initWithWindow:[[UIApplication sharedApplication] delegate].window];
[HUD showWhileExecuting:#selector(loginUserintoserver) onTarget:self withObject:nil animated:YES];
[[[UIApplication sharedApplication] delegate].window addSubview:HUD];
Hope it will help you .

Resources