I have a progress bar in my app showing a percent value.
progressView = [[DDProgressView alloc] initWithFrame:CGRectMake(20.0f, 140.0f, self.view.bounds.size.width - 40.0f, 0.0f)];
[progressView setOuterColor:[UIColor grayColor]];
[progressView setInnerColor:[UIColor lightGrayColor]];
[self.view addSubview:progressView];
[progressView release];
float randomPercentageFloat = 40;
progressView.progress = randomPercentageFloat / 100;
This shows a progress bar which is 40% full. I want to make the progress bar to show a value from a php. I have a php file that echoes a value. I want to change the randomPercentageFloat = 40; to something like
float randomPercentageFloat = "www.website.com/value.php";
Is this possible? How can it be done?
You have to establish connection with your server e retrieve the value, following the sample cose
test.php contains this instruction:
<?php echo 40; ?>
here sample viewController.m with progress view linked via Interface Builder
#import "ViewController.h"
#interface ViewController () {
IBOutlet UIProgressView *progressView;
NSMutableData *receivedData;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
progressView.progressTintColor = [UIColor lightGrayColor];
progressView.trackTintColor = [UIColor grayColor];
progressView.progress = 0.0f;
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.0.29/test.php"]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (!theConnection) {
UIAlertView *connectFailMessage = [[UIAlertView alloc] initWithTitle:#"NSURLConnection " message:#"Failed in viewDidLoad" delegate: self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[connectFailMessage show];
}
}
#pragma mark NSURLConnection Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
receivedData = [NSMutableData data];
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// inform the user
UIAlertView *didFailWithErrorMessage = [[UIAlertView alloc] initWithTitle: #"NSURLConnection " message: #"didFailWithError" delegate: self cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[didFailWithErrorMessage show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *dataString = [[NSString alloc] initWithData: receivedData encoding:NSUTF8StringEncoding];
progressView.progress = [dataString floatValue] / 100;
}
#end
Related
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;
}
}
I have a ViewController which has two segues and I want that segue to present viewcontroller after fetching data from URL. So I have kept preparesegueWithIdentifier in connectionDidFinishLoading method.
But I am able to show only first viewcontroller.
I want that both segues works properly.
#import "specialistquery.h"
#import "FitnessView.h"
#import "askCall.h"
#import "Header.h"
#interface specialistquery ()<UITextFieldDelegate,UITextViewDelegate>
{
NSMutableData *responseData;
UIAlertView *alert;
}
#end
#implementation specialistquery
#synthesize title,discription,title1,CallBackBtn,SubmitBtn;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
dataArray = [[NSArray alloc]initWithObjects:#"Yoga Specialist", #"Dietician", #"Fitness Specialist", #"Homeopathic", #"Ayurvedic Specialist", nil];
UIPickerView *picker = [[UIPickerView alloc]init];
picker.delegate=self;
picker.dataSource=self;
[picker setShowsSelectionIndicator:YES];
[self.selectspecs setInputView:picker];
//toolbar
UIToolbar *toolbar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
[toolbar setTintColor:[UIColor grayColor]];
UIBarButtonItem *doneBtn=[[UIBarButtonItem alloc]initWithTitle:#"Done" style:UIBarButtonItemStylePlain target:self action:#selector(showSelectedDate)];
UIBarButtonItem *space=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[toolbar setItems:[NSArray arrayWithObjects: space, doneBtn,nil]];
[self.selectspecs setInputAccessoryView:toolbar];
[self.title1 setInputAccessoryView:toolbar];
[self.discription setInputAccessoryView:toolbar];
}
-(void)showSelectedDate
{
[self.selectspecs resignFirstResponder];
[self.title1 resignFirstResponder];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"good"]) {
FitnessView *spec = [segue destinationViewController];
spec.str = _selectspecs.text;
}
if ([segue.identifier isEqualToString:#"callback"]) {
askCall *spec = [segue destinationViewController];
spec.str = _selectspecs.text;
}
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [dataArray count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [dataArray objectAtIndex:row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
self.selectspecs.text = [dataArray objectAtIndex:row];
}
- (IBAction)DisKey:(id)sender {
[self.selectspecs resignFirstResponder];
[self.title1 resignFirstResponder];
[self.discription resignFirstResponder];
}
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
{
if ([identifier isEqualToString:#"good"])
{
if ([title1.text isEqualToString:#""] || [discription.text isEqualToString:#""] || [_selectspecs.text isEqualToString:#""])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Oppss!!!" message:#"ALL FIELDS MUST BE FILLED" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil ];
[alert show];
return NO;
}
else
{
NSDate *todayDate = [NSDate date]; // get today date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // here we create NSDateFormatter object for change the Format of date..
[dateFormatter setDateFormat:#"dd-MM-yyyy"]; //Here we can set the format which we need
NSString *convertedDateString = [dateFormatter stringFromDate:todayDate];// here convert date in
NSString *url;
url=#"http://www.bha.com/mDru/index.php";
const char *bytes = [[NSString stringWithFormat:#"question=%#&description=%#&createddate=%#&createdby=iPhone&userid=519&tag=storequestion",title1.text,discription.text,convertedDateString ] UTF8String];
NSURL *url1 = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url1];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[NSData dataWithBytes:bytes length:strlen(bytes)]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
}
else if ([identifier isEqualToString:#"callback"])
{
if ([title1.text isEqualToString:#""] || [discription.text isEqualToString:#""] || [_selectspecs.text isEqualToString:#""])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Oppss!!!" message:#"ALL FIELDS MUST BE FILLED" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil ];
[alert show];
return NO;
}
else
{
NSDate *todayDate = [NSDate date]; // get today date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // here we create NSDateFormatter object for change the Format of date..
[dateFormatter setDateFormat:#"dd-MM-yyyy"]; //Here we can set the format which we need
NSString *convertedDateString = [dateFormatter stringFromDate:todayDate];// here convert date in
NSString *url;
url=#"http://www.bha.com/mDru/index.php";
const char *bytes = [[NSString stringWithFormat:#"question=%#&description=%#&createddate=%#&createdby=iPhone&userid=519&tag=storequestion",title1.text,discription.text,convertedDateString ] UTF8String];
NSURL *url1 = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url1];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[NSData dataWithBytes:bytes length:strlen(bytes)]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
}
return NO;
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
responseData = [[NSMutableData alloc] init];
alert = [[UIAlertView alloc] initWithTitle:#"Please Wait..." message:#"Saving Data" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
[alert show];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[alert dismissWithClickedButtonIndex:0 animated:YES];
UIAlertView *nsjsdn = [[UIAlertView alloc] initWithTitle:nil message:#"Internet connection problem" delegate:self cancelButtonTitle:#"Exit" otherButtonTitles:nil, nil];
[nsjsdn show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *teststr=[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSString *str1234 = [teststr stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSLog(#"Response is %# %lul",str1234,(unsigned long)
[str1234 length]);
[alert dismissWithClickedButtonIndex:0 animated:YES];
[self performSegueWithIdentifier:#"good" sender:self];
[self performSegueWithIdentifier:#"callback" sender:self];
}
#end
If you do this, I believe you should get the result you require.
Make IBOutlets button1 and button2 for your buttons and IBAction methods for your buttons and set its selected property to YES.
- (IBAction)button1Clicked:(id)sender
{
button1.selected = YES;
if (button2.selected)
{
// This is done so that both buttons do not appear as clicked at the same time
button2.selected = NO;
}
}
- (IBAction)button2Clicked:(id)sender
{
button2.selected = YES;
if (button1.selected)
{
// This is done so that both buttons do not appear as clicked at the same time
button1.selected = NO;
}
}
After this is done, in your connectionDidFinishLoading method do this check.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *teststr=[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSString *str1234 = [teststr stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSLog(#"Response is %# %lul",str1234,(unsigned long)
[str1234 length]);
[alert dismissWithClickedButtonIndex:0 animated:YES];
if (button1.selected)
{
[self performSegueWithIdentifier:#"good" sender:self];
}
else if (button2.selected)
{
[self performSegueWithIdentifier:#"callback" sender:self];
}
}
Hope it helps.
I am displaying a UIImage view with this code:
NSURL *imageUrl = [[NSURL alloc]initWithString:#"http://..."];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageUrl];
UIImage *audioArt =[[UIImage alloc] initWithData:imageData];
UIImageView *artView =[[UIImageView alloc] initWithImage:audioArt];
artView.contentMode = UIViewContentModeScaleAspectFit;
artView.autoresizesSubviews = NO;
artView.frame = viewRef.bounds;
[artView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
[artView setBackgroundColor:[UIColor blackColor]];
[viewRef setBackgroundColor:[UIColor blackColor]];
[viewRef addSubview:artView];
Is there an event in Objective C to tell when this UIImage has finished loading or when the UIImageView has finished displaying the image?
Many thanks.
in your .h
#interface YourClass : YourSuperclass<NSURLConnectionDataDelegate>
#property (nonatomic) NSMutableData *imageData;
#property (nonatomic) NSUInteger totalBytes;
#property (nonatomic) NSUInteger receivedBytes;
And somewhere call
NSURL *imageUrl = [[NSURL alloc]initWithString:#"http://..."];
NSURLRequest *request = [NSURLRequest requestWithURL: imageUrl];
NSURLConnection *connection = [NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
And also implement the delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) urlResponse;
NSDictionary *dict = httpResponse.allHeaderFields;
NSString *lengthString = [dict valueForKey:#"Content-Length"];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSNumber *length = [formatter numberFromString:lengthString];
self.totalBytes = length.unsignedIntegerValue;
[self.imageData = [[NSMutableData alloc] initWithLength:self.totalBytes];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.imageData appendData:data];
self.receivedBytes += data.length;
// Actual progress is self.receivedBytes / self.totalBytes
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
imageView.image = [UIImage imageWithData:self.imageData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//handle error
}
Update:
Since NSMutableData initWithLength: creates a data object whose raw data is filled with zeros, replace initWithLength: with just init and it will works.
UIImage doesn't have any delegate or callback which tells you about its successful loading.
If you are getting the image from any url, you can use NSURL's delegates and notifications to track if you received the image or not.
Also you can achieve it as :
- (void)loadImage:(NSString *)filePath {
[self performSelectorInBackground:#selector(loadImageInBackground:) withObject:filePath];
}
- (void)loadImageInBackground:(NSString *)filePath {
#autoreleasepool{
UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
[self performSelectorOnMainThread:#selector(didLoadImageInBackground:) withObject:image waitUntilDone:YES];
}
}
- (void)didLoadImageInBackground:(UIImage *)image {
self.imageView.image = image;
}
NSURL *url = [NSURL URLWithString:#"http://i0.kym-cdn.com/entries/icons/original/000/005/545/OpoQQ.jpg?1302279173"];
NSData *data = [NSData dataWithContentsOfURL:url];
imageView.image = [[[UIImage imageWithData:data];
I want to set progress bar while downloading.
To give a more detailed example:
in your .h file do
#interface YourClass : YourSuperclass<NSURLConnectionDataDelegate>
in your .m file do
#property (nonatomic) NSMutableData *imageData;
#property (nonatomic) NSUInteger totalBytes;
#property (nonatomic) NSUInteger receivedBytes;
And somewhere call
NSURL *url = [NSURL URLWithString:#"http://i0.kym-cdn.com/entries/icons/original/000/005/545/OpoQQ.jpg?1302279173"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
And also implement the delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) urlResponse;
NSDictionary *dict = httpResponse.allHeaderFields;
NSString *lengthString = [dict valueForKey:#"Content-Length"];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSNumber *length = [formatter numberFromString:lengthString];
self.totalBytes = length.unsignedIntegerValue;
self.imageData = [[NSMutableData alloc] initWithCapacity:self.totalBytes];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.imageData appendData:data];
self.receivedBytes += data.length;
// Actual progress is self.receivedBytes / self.totalBytes
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
imageView.image = [UIImage imageWithData:self.imageData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//handle error
}
You can't get progress call backs by using that method.
You need to use an NSURLConnection and NSURLConnectionDataDelegate.
The NSURLConnection then runs asynchronously and will send callbacks to its delegate.
The main ones to look at are...
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
and
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
These are all used for getting the connection to do what you're already doing.
EDIT
Actually, see Marc's answer below. It is correct.
You can use MBProgress Hud class for loading view. You can download only two classes from here :-https://github.com/jdg/MBProgressHUD
After you write this code in that class which you want to load the data
Example :In your viewDidLoad you write this
- (void) viewDidLoad
{
MBProgressHud *spinner = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
spinner.mode = MBProgressHUDModeCustomView;
[spinner setLabelText:#"Loading....."];
[spinner setLabelFont:[UIFont systemFontOfSize:15]];
[spinner show:YES];
[self performSelectorInBackground:#selector(getData) withObject:nil];
}
- (void) getData
{
NSURL *url = [NSURL URLWithString:#"http://i0.kym-cdn.com/entries/icons/original/000/005/545/OpoQQ.jpg?1302279173"];
NSData *data = [NSData dataWithContentsOfURL:url];
imageView.image = [[[UIImage imageWithData:data];
[spinner hide:YES];
[spinner removeFromSuperViewOnHide];
}
I am beginner in IOS programming. My question is my app fetching data from JSON in my web server, when starting the apps, it is slightly lag and delay due to the fetching process, so i would like to show activity indicator when i connecting to JSON data. How can i do that?
My JSON coding:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *urlAddress = [NSURL URLWithString:#"http://emercallsys.webege.com/RedBoxApp/getEvents.php"];
NSStringEncoding *encoding = NULL;
NSError *error;
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:urlAddress usedEncoding:encoding error:&error];
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (dict)
{
eventsDetail = [[dict objectForKey:#"eventsDetail"] retain];
}
[jsonreturn release];
}
use the following code
//add a UIActivityIndicatorView to your nib file and add an outlet to it
[indicator startAnimating];
indicator.hidesWhenStopped = YES;
dispatch_queue_t queue = dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
//Load the json on another thread
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:urlAddress usedEncoding:encoding error:NULL];
[jsonreturn release];
//When json is loaded stop the indicator
[indicator performSelectorOnMainThread:#selector(stopAnimating) withObject:nil waitUntilDone:YES];
});
You can use something like below code:
- (void)fetchData
{
[activityIndicator startAnimating];
NSURL *url = [NSURL URLWithString:strUrl];
NSURLRequest *theRequest = [[NSURLRequest alloc]initWithURL:url];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(theConnection) {
}
else {
NSLog(#"The Connection is NULL");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
webData = [[NSMutableData data] retain];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction %#",error);
UIAlertView *connectionAlert = [[UIAlertView alloc] initWithTitle:#"Information !" message:#"Internet / Service Connection Error" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[connectionAlert show];
[connectionAlert release];
[connection release];
[webData release];
return;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
//NSLog(#"Received data :%#",theXML);
//[theXML release];
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary: webData error:&error];
if (dict) {
eventsDetail = [[dict objectForKey:#"eventsDetail"] retain];
}
[activityIndicator stopAnimating];
}