i've created a UICollectionView inside a ViewController. My UiCollectionViewCell contains a imageview and a label. It seems like it is really bad at handling click events. i need to click a lot of times before it react for the click. often it only do it on double tap.
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSString *urlString2 = [NSString stringWithFormat:#"http://ratemyplays.com/songs.php?listid=%d", indexPath.row];
NSMutableURLRequest *request2 = [[NSMutableURLRequest alloc]init];
[request2 setTimeoutInterval:20.0];
[request2 setURL:[NSURL URLWithString:urlString2]];
[request2 setHTTPMethod:#"POST"];
NSString *PHPArray = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:request2 returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];
NSArray *playArray2 = [PHPArray componentsSeparatedByString:#"."];
if ([playArray2 count] <2) {
UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:#"This Playlist is empty!!" message:#"We're Currently modifying it" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert2 show];
} else {
YouTubeTableViewController *youTubeTableViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"YouTubeTableViewController"];
youTubeTableViewController.selectedRowValue=indexPath.row;
[self.navigationController pushViewController:youTubeTableViewController animated:YES];
youTubeTableViewController.titleName = scoreArray;
youTubeTableViewController.playlistId = scoreArray2;
}
}
Is this normal behavior or am i missing something?
You are doing a synchronous request when the cell is clicked, and it may be causing this "feeling" that you have to click several times. I suggest you change the NSURLConnection synchronous request to an asynchronous one. Like this:
[NSURLConnection sendAsynchronousRequest:request
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if (error == nil)
{
NSString *PHPArray = =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"data received from url: %#", PHPArray);
if ([playArray2 count] <2) {
UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:#"This Playlist is empty!!" message:#"We're Currently modifying it" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert2 show];
} else {
YouTubeTableViewController *youTubeTableViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"YouTubeTableViewController"];
youTubeTableViewController.selectedRowValue=indexPath.row;
[self.navigationController pushViewController:youTubeTableViewController animated:YES];
youTubeTableViewController.titleName = scoreArray;
youTubeTableViewController.playlistId = scoreArray2;
}
}
else if (error != nil && error.code == NSURLErrorTimedOut)
{
NSLog(#"error code: %ld", (long)error.code);
}
else if (error != nil)
{
NSLog(#"error code: %ld", (long)error.code);
}
}];
Do you have your label and image enabled for user interaction?
Related
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..
I have used URLRequest to fetch a html file from a pc in my wifi network.
My app fetches a html file from my fileserver and the filename is a number which is typed in the app. Also I have given a 20 seconds timeout for the request. How can I detect whether timeout occurred because I have 2 situations,
1. file does not exist
2. connection is slow
In urlrequest, there is a BOOL for error,no description.
Suggest me a method if possible.
My code is below for only urlrequest
-(void)getHtmlContent{
[self.spinner startAnimating];
NSString *str = #"http://192.168.1.250/rec/";
// NSString *str = #"file:///Volumes/xampp/htdocs/";
str = [str stringByAppendingString:numEntered.text];
str = [str stringByAppendingString:#".html"];
NSURL *url=[NSURL URLWithString:str];
//self.htmlContent = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//NSURLRequest *request = [NSURLRequest requestWithURL:url];
request.timeoutInterval = 20.0;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *localfile, NSURLResponse *response, NSError *error) {
if(!error){
if([request.URL isEqual:url]){
NSString *content = [NSString stringWithContentsOfURL:localfile encoding: NSUTF8StringEncoding error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
[numEntered setText:#"0"];
text = #"";
[self.spinner stopAnimating];
self.htmlContent = content;
NSString *myHTMLString = self.htmlContent;
if(myHTMLString != nil) {
if([myHTMLString isEqualToString:#"3"]){
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"LogIn Success" message:#"" delegate:self cancelButtonTitle:#"Continue" otherButtonTitles:nil];
self.view.userInteractionEnabled = YES;
[alrt show];
}
else{
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"LogIn Failed. Try again." message:#"User not authenticated" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
self.view.userInteractionEnabled = YES;
[alrt show];
}
}
});
}
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
[self.spinner stopAnimating];
[numEntered setText:#"0"];
text = #"";
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"Requested file does not exist." message:#"Try again." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
self.view.userInteractionEnabled = YES;
[alrt show];
});
}
}];
[task resume];
}
Since I can not comment I am writing as an Answer.
You need to check the error object to see the type of error that occured.
so in your else block you need to check error.localizedDescription to see what has happened, it would usually tell you that the file was not found or if the request timed out. you can even use your alert to show it like changing your else block as follows
else {
dispatch_async(dispatch_get_main_queue(), ^{
[self.spinner stopAnimating];
[numEntered setText:#"0"];
text = #"";
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle : #"Error"
message : error.localizedDescription
delegate : self
cancelButtonTitle : #"Ok"
otherButtonTitles : nil];
self.view.userInteractionEnabled = YES;
[alrt show];
});
}
You must use this delegate method to handle timeout:-
-(void) connection:(NSURLConnection * ) connection didFailWithError:(NSError *)error {
if (error.code == NSURLErrorTimedOut)
// handle error as you want
NSLog(#"Request time out");
}
I need to show a UIActivityIndicatorView when calling of a WebService is take place. However, the activity indicator keeps on showing even after i have received response from web service. It stops only after 5-6 seconds after i receive response. How to make it stop at the moment i am receiving a response?
Here's my code: (configuring UIActivityIndicatorView) and calling my webservice:
loadView = [[UIView alloc] initWithFrame:self.view.bounds];
loadView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
//UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] init];
//[second.loadingView addSubview:activityView];
//activityView.center = second.loadingView.center;
//[second.view addSubview:second.loadingView];
activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[loadView addSubview:activity];
activity.center = loadView.center;
[self.view addSubview:loadView];
[self.view bringSubviewToFront:loadView];
activity.hidesWhenStopped = YES;
[activity setHidden:NO];
//[activity performSelectorInBackground: #selector(startAnimating) withObject: nil];
[activity startAnimating];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self callRegisterWebService:self.userFname lastName:self.userLName email:self.userEmail];
});
I am stopping the animation in the finally block.
-(void)callRegisterWebService:(NSString *)fname lastName:(NSString *)lName email:(NSString *)email
{
NSString *serviceURL = [NSString stringWithFormat:#"https:abcdefghi..."];
#try {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
NSURLResponse *serviceResponse = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&serviceResponse error:&err];
NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
if(!parsedData)
{
NSLog(#"data not parsed");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
else
{
NSString *status = [parsedData objectForKey:#"Status"];
if([status isEqualToString:#"Success"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NULL message:#"Authentication Token Has Been Sent To Your Email-ID!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
NSString *uniqueNumber = [parsedData objectForKey:#"UniqueNum"];
[self saveEmailAndUniqueNumberToDatabase:fname lastName:lName Email:email Number:uniqueNumber];
}
else if([status isEqualToString:#"Failed"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Not An Authorized User" message:#"Please Contact Admin To Get Access" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}
}
#catch (NSException *exception)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NULL message:#"Problem In Network Connection. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
#finally {
[activity stopAnimating];
[loadView setHidden:YES];
}
}
There are 2 issues in your code:
You are manipulating UI component from a background thread, never do that. Use main thread for UI manipulations
You wrote the activity indicator functionality in the finally clause, so it'll be hidden only after executing all the statements in try clause
Change your method like:
- (void) hideActivity
{
dispatch_async(dispatch_get_main_queue(), ^{
[activity stopAnimating];
[loadView setHidden:YES];
activity = nil;
loadView = nil;
});
}
-(void)callRegisterWebService:(NSString *)fname lastName:(NSString *)lName email:(NSString *)email
{
NSString *serviceURL = [NSString stringWithFormat:#"https:abcdefghi..."];
NSString *message = #"";
NSString *title = #"";
#try
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
NSURLResponse *serviceResponse = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&serviceResponse error:&err];
NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
[self hideActivity];
if(!parsedData)
{
message = #"Problem in Network. Please Try Again!";
title = #"ERROR";
}
else
{
NSString *status = [parsedData objectForKey:#"Status"];
if([status isEqualToString:#"Success"])
{
message = #"Authentication Token Has Been Sent To Your Email-ID!";
title = nil;
NSString *uniqueNumber = [parsedData objectForKey:#"UniqueNum"];
[self saveEmailAndUniqueNumberToDatabase:fname lastName:lName Email:email Number:uniqueNumber];
}
else if([status isEqualToString:#"Failed"])
{
message = #"Please Contact Admin To Get Access";
title = #"Not An Authorized User";
}
else
{
message = #"Problem in Network. Please Try Again!";
title = #"ERROR";
}
}
}
#catch (NSException *exception)
{
if (activity != nil && loadView != nil)
{
[self hideActivity];
}
message = #"Problem In Network Connection. Please Try Again!";
title = nil;
}
#finally
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}
I have an app which does an async post to a server. Then it decodes the json and returns the message from the server. I put a few debugging log entries in my code, so I know that the response from the server, as well as the decoding of the json are instantaneous. The problem is that after the json is decoded, the async task runs for about 6 seconds before it calls the next event (Showing the popup dialog).
- (IBAction)register:(id)sender {
[self startPost]; // Starts spinner animation
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self doPost]; // performs post
});
}
-(void)doPost
{
#try {
NSString *post =[[NSString alloc] initWithFormat:#"request=register&platform=ios&email=%#&password=%#",self.email.text,self.password.text];
//NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"https://site.com/api.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//NSLog(#"Response code: %d", [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
//NSLog(#"Response ==> %#", responseData);
NSData *responseDataNew = [responseData dataUsingEncoding:NSUTF8StringEncoding];
NSError* error = nil;
NSDictionary *myDictionary = [NSJSONSerialization JSONObjectWithData:responseDataNew options:NSJSONReadingMutableContainers error:&error];
if ( error ){
[self alertStatus:#"Unknown response code from server" :#"Whoops!"];
NSLog(#"Response ==> %#", responseData);
[self postDone];
}else{
if ([myDictionary[#"error"] isEqualToNumber:(#1)])
{
NSLog(#"ERROR DETECTED");
[self alertStatus:myDictionary[#"message"]:#"Whoops!"];
[self postDone];
}
else
{
[self alertSuccess];
[self postDone];
}
}
} else {
if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Connection Failed" :#"Whoops!"];
[self postDone];
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Registration Failed." :#"Whoops!"];
[self postDone];
}
}
-(void)startPost
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
self.email.enabled = false;
self.password.enabled = false;
self.confirm.enabled = false;
self.cancelButton.enabled = false;
}
- (void) alertStatus:(NSString *)msg :(NSString *)title
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView setTag:0];
[alertView show];
}
- (void) alertSuccess
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Success!"
message:#"You have been successfully registered."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView setTag:1];
[alertView show];
}
-(void)postDone
{
self.registerButton.hidden = false;
self.spinner.hidden = true;
self.loadingText.hidden = true;
//[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
self.email.enabled = true;
self.password.enabled = true;
self.confirm.enabled = true;
self.cancelButton.enabled = true;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{if (alertView.tag == 1)
{
[self dismissViewControllerAnimated:YES completion:nil];
}}
The alertStatus and alertSuccess functions just pop up a message box briefly.
When I run the code, I purposefully enter bad information so the log says "ERROR DETECTED". The problem is that it takes another 6 seconds before anything happens after that.
After you have called:
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
and obtained the data, you should switch back to the main thread to use it. This is because all UI updates must be done on the main thread.
So, all that code after you get the data should be moved to a new method and called as:
dispatch_async(dispatch_get_main_queue(), ^{
[self handleData:urlData withResponse:response error:error];
}
And you should also put the exception catch code inside dispatch_async(dispatch_get_main_queue(), ^{ because you try to update the UI there too...
I am new ios, i use storyboard to implement list data function demo, include add data.
In my AddWrokLogViewController,I have a method (IBAction)done:(id)sender bind + button.
as follow, in my do function, I want to check user inputs and save user input datas by http post. when post data in remote save success, I want go back to list view.
as before I search apple article introduction storyboard, but in this demo, when user tap add button,direct transfer to list page view :http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/SecondiOSAppTutorial/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011318-CH1-SW1
If I use AFHTTPClient to save data in remote server success, then go back to list page view, or still in add page view and display error message.
any one can give me some suggestions, thanks!
NSString *url = [NSString stringWithFormat:#"%#",api_createworklog];
NSDictionary *params=[NSDictionary dictionaryWithObjectsAndKeys:uname,#"loginname",token,#"token",beginTime
,#"beginTime",content,#"content",address,#"address",projectNameTemp,#"projectName"
,workType,#"workType",workDate,#"workDate",validDate,#"validDate", nil];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL]];
[client postPath:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseString = [operation responseString];
NSDictionary *data = [responseString objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
NSString *sysCode = [data objectForKey:#"syscode"];
NSString *businessCode = [data objectForKey:#"businesscode"];
if(sysCode != nil && ![sysCode isEqualToString:#""] && businessCode != nil && ![businessCode isEqualToString:#""]){
if([sysCode isEqualToString:ws_access_success] && [businessCode isEqualToString:ws_access_success]){
//[self.navigationController popViewControllerAnimated:YES];
addSuccess = true;
} else{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"添加失败" message:responseString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertView show];
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSString *responseString = operation.responseString;
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"访问服务器异常,添加失败!" message:responseString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertView show];
}];