В этом небольшом уроке рассказывается о том, как можно получить данные с удаленного сервера и отобразить их в Вашем iOS приложении.
Запустите XCode и создайте новое View base приложение. В качестве имени проекта задайте ”ReceiveData”.
Давайте добавим в приложение UIViewController, для этого выберем project -> New File -> Cocoa Touch -> ViewController subclass. Назовем новый класс “DisplayData”.
Укажем DisplayData класс в ReceiveDataViewController.h. Создадим экземпляр UIButton и определим один IBAction: метод.
#import <UIKit/UIKit.h> @class DisplayData; @interface ReceiveDataViewController: UIViewController{ UIButton*button; DisplayData*displayData; } @property(nonatomic,retain) IBOutlet UIButton*button; -(IBAction)DisplayData:(id)sender; @end
Дважды щелкнем по ReceiveDataViewController.xib, чтобы запустить редактор интерфейса. Разместим на шаблоне окна кнопку. С помощью Connection Inspector свяжем событие кнопки Touch Up Inside с методом DisplayData. Сохраним результат.
Дважды щелкнем по ReceiveDataViewController.m и напишем реализацию метода DisplayData:
#import "ReceiveDataViewController.h" #import "DisplayData.h" @implementation ReceiveDataViewController @synthesize button; -(IBAction)DisplayData:(id)sender { displayData=[[DisplayData alloc] initWithNibName:@"DisplayData" bundle:nil]; [self.view addSubview:displayData.view]; } -(void)dealloc { [super dealloc]; } -(void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } #pragma mark – View lifecycle -(void)viewDidUnload { [super viewDidUnload]; } -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return(interfaceOrientation== UIInterfaceOrientationPortrait); } @end
Откроем файл DisplayData.h и внесем в него следующие изменения:
#import <UIKit/UIKit.h> @interface DisplayData: UIViewController{ NSMutableData*webData; UIScrollView*titleScrollView; UITextView*textView; UIActivityIndicatorView* loadIndicator; } @property(nonatomic, retain) NSMutableData*webData; @property(nonatomic,retain) IBOutlet UIScrollView*titleScrollView; @property(nonatomic, retain) UIActivityIndicatorView*loadIndicator; -(void)ActivityIndigator; @end
Откроем DisplayData.xib в Interface Builder и перетащим на макет scrollview. Свяжем File’s Owner с titleScrollView. Сохраним результат.
Откроем DisplayData.m
#import "DisplayData.h" @implementation DisplayData @synthesize webData,titleScrollView,loadIndicator; -(id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil { self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if(self){ // Custom initialization } returnself; } -(void)dealloc { [super dealloc]; } -(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. } #pragma mark – View lifecycle -(void)ActivityIndigator { loadIndicator= [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(130,200,40,40)]; loadIndicator.activityIndicatorViewStyle= UIActivityIndicatorViewStyleWhiteLarge; [loadIndicator startAnimating]; [self.view addSubview:loadIndicator]; [loadIndicator release]; } -(void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. [self ActivityIndigator]; NSURL*url=[NSURL URLWithString:@"http://www.chakrainteractive.com/mob//ReceiveData/Data.txt"]; NSMutableURLRequest*theRequest=[NSMutableURLRequest requestWithURL:url]; NSURLConnection*theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if( theConnection) { webData=[[NSMutableData data] retain]; } else { } } -(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response { [webData setLength:0]; } -(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data { [webData appendData:data]; } -(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error { UIAlertView*alert=[[UIAlertView alloc] initWithTitle:@"Error" message:@"An error has occured.Please verify your internet connection." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; [loadIndicator removeFromSuperview]; [connection release]; [webData release]; } -(void)connectionDidFinishLoading:(NSURLConnection*)connection { NSLog(@"DONE. Received Bytes:%d",[webData length]); NSString*loginStatus=[[NSString alloc] initWithBytes:[webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]; textView=[[UITextView alloc] initWithFrame:CGRectMake(5,30,320,400)];//size.height-30 )]; textView.text= loginStatus; [textView setFont:[UIFont systemFontOfSize:14]]; [textView setBackgroundColor:[UIColor clearColor]]; [textView setTextColor:[UIColor blackColor]]; textView.editable= NO; textView.dataDetectorTypes= UIDataDetectorTypeNone; [loadIndicator removeFromSuperview]; [titleScrollView addSubview:textView]; [loginStatus release]; [textView release]; [connection release]; [webData release]; } -(void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return(interfaceOrientation== UIInterfaceOrientationPortrait); } @end
Сохраним и попробуем запустить приложение.