Updating the UI control's value in the runtime from background thread. - multithreading

I know this sound a very simple question. I'm still a newbie in iPad app development. Would you please tell me how would I update the contents in the run time. The following code may be helpful to know my question in detail.
In the following code, I'm trying to display text contents in the TexViewcontrol. When I change the for loop form 10 to 100000, I needed to wait until everything fills up. I need to display the contents on the screen while loop is running.
- (IBAction)RunHelloWorld:(id)sender
{
tctView.text = #"tt";
for(int i=0;i<10;i++)
{
NSString *result1 = #"Testing";
tctView.text = [tctView.text stringByAppendingString:result1];
tctView.scrollEnabled = YES;
}
}
Would you please give me any help? Thanks a LOT!!!
-Teva

Finally I found the solution with the following URL's help. http://samplecodebank.blogspot.com/2011/05/nsthread-example_12.html
Thanks a LOT!
This is my code.
PCViewController.h file code
#import <UIKit/UIKit.h>
#interface PCViewController : UIViewController
{
IBOutlet UITextView *txtView;
}
-(void)ReadFile;
- (void) mainThreadSetText:(NSString*)text;
#end
PCViewController.m file code
#import "PCViewController.h"
#interface PCViewController ()
#end
#implementation PCViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[NSThread detachNewThreadSelector:#selector(ReadFile) toTarget:self withObject:nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(void)ReadFile
{
// Check whether current thread is externally terminated or not.
char line[1024];
FILE *fp = fopen("/Users/Teva/Desktop/File1.txt","r");
while([[NSThread currentThread] isCancelled] == NO)
{
if( fp != NULL )
{
while( fgets(line,1024,fp) )
{
printf("%s\n",line);
NSString *result1 = [NSString stringWithCString:line encoding:NSASCIIStringEncoding];
[self performSelectorOnMainThread:#selector(mainThreadSetText:) withObject:result1 waitUntilDone:YES];
[NSThread sleepForTimeInterval:1.0];
}
}
}
}
// Screen processing should be done outside the Thread.
- (void) mainThreadSetText:(NSString*)text
{
txtView.text = [txtView.text stringByAppendingString:text];
txtView.scrollEnabled = YES;
}
- (void)dealloc
{
[txtView release];
[super dealloc];
}
#end

Related

Using GCD to Parse KML With Apple's KMLViewer

I'm using Apple's KMLViewer to load a KML file and display it in a MapView. There are over 50,000 lines of coordinates in the KML file which, of course, causes it to load slowly. In an attempt to speed things up, I'm trying to perform the parsing in another thread using GCD.
I have it working reasonably well as far as it is displaying properly and the speed is acceptable. However, I'm getting intermittent runtime errors when loading the map. I suspect it is because the way I have things laid out, the UI is being updated within the GCD block. Everything I'm reading says the UI should be updated in the main thread or else runtime errors can occur which are intermittent and hard to track down. Well, that's what I'm seeing.
The problem is, I can't figure out how to update the UI in the main thread. I'm still new to iOS programming so I'm just throwing things against the wall to see what works. Here is my code, which is basically Apple's KMLViewerViewController.m with some modifications:
#import "KMLViewerViewController.h"
#implementation KMLViewerViewController
- (void)viewDidLoad
{
[super viewDidLoad];
activityIndicator.hidden = TRUE;
dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL);
dispatch_async(myQueue, ^{
// Locate the path to the route.kml file in the application's bundle
// and parse it with the KMLParser.
NSString *path = [[NSBundle mainBundle] pathForResource:#"BigMap" ofType:#"kml"];
NSURL *url = [NSURL fileURLWithPath:path];
kmlParser = [[KMLParser alloc] initWithURL:url];
[kmlParser parseKML];
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI
// Add all of the MKOverlay objects parsed from the KML file to the map.
NSArray *overlays = [kmlParser overlays];
[map addOverlays:overlays];
// Add all of the MKAnnotation objects parsed from the KML file to the map.
NSArray *annotations = [kmlParser points];
[map addAnnotations:annotations];
// Walk the list of overlays and annotations and create a MKMapRect that
// bounds all of them and store it into flyTo.
MKMapRect flyTo = MKMapRectNull;
for (id <MKOverlay> overlay in overlays) {
if (MKMapRectIsNull(flyTo)) {
flyTo = [overlay boundingMapRect];
} else {
flyTo = MKMapRectUnion(flyTo, [overlay boundingMapRect]);
}
}
for (id <MKAnnotation> annotation in annotations) {
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
if (MKMapRectIsNull(flyTo)) {
flyTo = pointRect;
} else {
flyTo = MKMapRectUnion(flyTo, pointRect);
}
}
// Position the map so that all overlays and annotations are visible on screen.
map.visibleMapRect = flyTo;
});
});
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
activityIndicator.hidden = FALSE;
[activityIndicator startAnimating];
}
#pragma mark MKMapViewDelegate
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
return [kmlParser viewForOverlay:overlay];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
return [kmlParser viewForAnnotation:annotation];
}
- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView
{
[activityIndicator stopAnimating];
activityIndicator.hidden = TRUE;
}
#end
Suggestions?

Subview not closing causing Memory Leak Phonegap

I am having issues not being able to close CDVViewController when calling this custom refresh, it stays loaded in the background and loads a new one causing memory leaks/high memory usage. I have tried to use both release and removeFromSuperview for the webView, subview, CDVViewController, ChildViewController but none of them work. I am running a Tab Bar Controller via Storyboard, (another reason why I have to call CDVViewController as a subview) and when I use the web inspector via safari I can see the pages building up on that tab, and when I refresh on another tab (not using CDVViewController/phonegap) it works fine. Any help is much appreciated.
So here is my .h
#import <UIKit/UIKit.h>
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <Cordova/CDVViewController.h>
#interface ThirdViewController : CDVViewController <UIWebViewDelegate>
{
IBOutlet CDVViewController *webView;
IBOutlet UIActivityIndicatorView *activityind;
}
- (IBAction)Refresh:(id)sender;
#end
And my .m
#interface ThirdViewController ()
#end
#implementation ThirdViewController
- (void)viewDidLoad
{
webView = [CDVViewController new];
webView.startPage = #"MYWEBSITE";
[self addChildViewController:webView];
[self.webView addSubview:webView.view];
webView.view.frame = CGRectMake(0, 0, 0, 0);
[activityind startAnimating];
[self.webView addSubview: activityind];
[self CustomActivity];
}
-(void) CustomActivity
{
if ([webView.reference isEqualToString:#"TRUE"]){ //webView.reference is something I added into phonegap CDVViewController so that I am able to see when it is being loaded/used to load the custom activity/activity ind to work.
[activityind removeFromSuperview];
}else{
[NSTimer scheduledTimerWithTimeInterval:.5 target:self selector:#selector(CustomActivity) userInfo:nil repeats:NO];
}
}
- (IBAction)Refresh:(id)sender {
webView = [CDVViewController new];
webView.startPage = #"MYWEBSITE";
[self addChildViewController:webView];
[self.webView addSubview:webView.view];
webView.view.frame = CGRectMake (0,0,self.view.frame.size.width,(self.view.frame.size.height -44));
[activityind startAnimating];
[self.webView addSubview: activityind];
[self CustomActivity];
}
- (void)webViewDidStartLoad:(UIWebView *)webView {}
- (void)webViewDidFinishLoad:(UIWebView *)subview {}
- (void)loading {}
- (void)didReceiveMemoryWarning{[super didReceiveMemoryWarning];}
#end
Found the solution, I had to implement [webView.webView reload];
- (IBAction)Refresh:(id)sender {
[webView.webView reload];
}

uiwebview not loading any content

I am not able to load any webpages.
Any idea why this could be?
The frame for the webview (printed from the debugger)
<UIWebView: 0x8a49840; frame = (0 0; 320 241); autoresize = TM+BM; layer = <CALayer: 0x8a498f0>>
Here is my code:
#import "ViewController.h"
#interface ViewController () <UIWebViewDelegate>
#end
#implementation ViewController
#synthesize webview;
- (void)viewDidLoad
{
[super viewDidLoad];
self.webview.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewDidAppear:(BOOL)animated
{
}
- (IBAction)buttonPress:(id)sender {
NSLog(#"pressed");
NSURL *theUrl = [NSURL URLWithString:#"www.google.com"];
NSError *e ;
// just for test - ALSO returning nil!!!
NSString *str = [NSString stringWithContentsOfURL:theUrl encoding:NSUTF8StringEncoding error:&e];
NSLog(#"%#",str);
NSURLRequest *theRequest = [NSURLRequest requestWithURL:theUrl];
[self.webview loadRequest:theRequest];
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSLog(#"page is loading");
}
// this method is never called
-(void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(#"finished loading");
}
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
return YES;
}
#end
use this one it'l work.
problem: in your url http:// was missed
NSURL *theUrl = [NSURL URLWithString:#"http://www.google.com"];
You don't have proper URL.
Because +URLWithString: expects a protocol (e.g. http://, https://),
if you have www.google.com in that case it cannot build a URL.So please try to use like this..
NSURL *url = [NSURL URLWithString:#"http://www.google.com"];
You may also check if your link doesn't contain the "http://" or "https://" and add it.
NSString *website = #"www.google.com";
NSRange textRangeHTTP = [[website lowercaseString] rangeOfString:#"http://"];
NSRange textRangeHTTPS = [[website lowercaseString] rangeOfString:#"https://"];
if((textRangeHTTP.location == NSNotFound) && (textRangeHTTPS.location == NSNotFound))
website = [NSString stringWithFormat:#"http://%#",website];
NSURL *theUrl = [NSURL URLWithString:website];
just use this in your buttoned pressed method
NSURL *theUrl = [NSURL URLWithString:#"http://www.google.com"];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:theUrl];
[self.webview loadRequest:theRequest];
always make sure that using the protocol type that is "http://" is prefixed to the web url string
(Xcode 5 iOS 7) Needed to update an Universal App for iOS 7 and Xcode 5. It is an open source project / example located here: Link to SimpleWebView (Project Zip and Source Code Example)

"Type name requires a specifier or qualifier" error

I have the following code but can't compile it because I have a "Type name requires a specifier or qualifier" error" for (self).
How to fix this error? I have compared it with the original code and there are no differences, so I don't know what's going on.
#import "CurrentTimeViewController.h"
#implementation CurrentTimeViewController
{
// Call the superclass's designated initializer
self = [super initWithNibName:#"CurrentTimeViewController"
bundle:nil];
if (self) {
// Get the tab bar item
UITabBarItem *tbi = [self tabBarItem];
// Give it a label
[tbi setTitle:#"Time"];
}
return self;
}
Here is the code from the mirror file HynososViewController.h, and which I cut, pasted and modified:
#import "HypnososViewController.h"
#implementation HypnososViewController
- (id) init
{
// Call the superclass's designated initializer
self = [super initWithNibName:nil
bundle:nil];
if (self) {
// Get the tab bar item
UITabBarItem *tbi = [self tabBarItem];
// Give it a label
[tbi setTitle:#"Hypnosis"];
}
return self;
}
- (id) initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle
{
// Disregard parameters - nib name is an implementation detail
return [self init];
}
// This method gets called automatically when the view is created
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"Loaded the view for HypnosisViewController");
// Set the background color of the view so we can see it
[[self view] setBackgroundColor:[UIColor orangeColor]];
}
#end
Here is the complete code for CurrentTimeViewController.h:
#import "CurrentTimeViewController.h"
#implementation CurrentTimeViewController
{
// Call the superclass's designated initializer
self = [super initWithNibName:#"CurrentTimeViewController"
bundle:nil];
if (self) {
// Get the tab bar item
UITabBarItem *tbi = [self tabBarItem];
// Give it a label
[tbi setTitle:#"Time"];
}
return self;
}
- (id) initWithNibName:(NSString *)nibName bundle:(NSBundle *)Bundle
{
// Disregard parameters - nib name is an implementation detail
return [self init];
}
// This method gets called automatically when the view is created
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"Loaded the view for CurrentTimeViewController");
// Set the background color of the view so we can see it
[[self view] setBackgroundColor:[UIColor greenColor]];
}
#end
Is the code above a cut-and-paste of EXACTLY what you are trying to compile? If so, I think you are missing something very important that would make that code block a method implementation:
-(id)init // This, or something like it, is missing???
{
...
}
Check your code, here, and in your project. :-)

iphone gmail code examples

I want to display login window and then type login and password credencial it will open the account. So i tried but it shows error like
/81: error: 'didReceiveMemoryWarning' undeclared (first use in this function)
*:81: error: expected ';' before '{' token*
100: error: expected declaration or statement at end of input
and i posted below the code please help
Thanks in advance
.h file
#import <UIKit/UIKit.h>
#interface Password1ViewController : UIViewController {
UITextField *textfieldName;
UITextField *textfieldPassword;
}
#property (nonatomic, retain) IBOutlet UITextField *textfieldName;
#property (nonatomic, retain) IBOutlet UITextField *textfieldPassword;
#end
.m file
#import "Password1ViewController.h"
#implementation Password1ViewController
#synthesize textfieldName;
#synthesize textfieldPassword;
-(void)alertView:(UIAlertView *)alertview clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex != [alertview cancelButtonIndex])
{
NSLog(#"Name: %#", textfieldName.text);
NSlog(#"Name: %#", textfieldPassword.text);
}
}
-(void) someMethod
{
UIAlertView *alert =[[UIAlertView alloc] initWithTitle:#"Please Login" message:#"" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Submit",nil];
[alert addTextFieldWithValue:#"" label:#"User Name"];
[alert addTextFieldWithValue:#"" label:#"Password"];
textfieldName = [alert textFieldAtIndex:0];
textfieldName.keyboardType = UIKeyboardTypeAlphabet;
textfieldName.keyboardAppearance = UIKeyboardAppearanceAlert;
textfieldName.autocorrectionType = UITextAutocorrectionTypeNo;
textfieldPassword = [alert textFieldAtIndex:1];
textfieldPassword.clearButtonMode = UITextFieldViewModeWhileEditing;
textfieldPassword.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
textfieldPassword.keyboardAppearance = UIKeyboardAppearanceAlert;
textfieldPassword.autocorrectionType = UITextAutocorrectionTypeNo;
textfieldPassword.secureTextEntry = YES;
[alert show];
}
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[textfieldName release];
[textfieldPassword release];
[super dealloc];
}
#end
You were missing a closing brace which I corrected in my edit. So, try now with the edited code.

Resources