Web Service也叫XML Web Service WebService是一种可以接收从Internet或者其它系统中传递过来的请求,轻量级的独立的通讯技术。
#import <UIKit/UIKit.h> //遵循NSURLConnectionDataDelegate协议 @interface ViewController : UIViewController<NSURLConnectionDataDelegate> //接受从服务器返回的数据 @property(strong,nonatomic) NSMutableData *datas; //开始请求web service -(void)starRequest; @end
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self starRequest]; } -(void)starRequest { //获取文件访问的路径 NSString *path=@"http://1.studyios.sinaapp.com/getAllClass.php"; // path=[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //封装URL NSURL *url=[NSURL URLWithString:path]; //创建请求对象 NSURLRequest *request=[[NSURLRequest alloc] initWithURL:url]; //实例化NSURLConnection,request请求对象,delegate是指定的委托对象 NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self]; if (connection) { self.datas=[NSMutableData new]; } } //请求成功并建立连接后,开始就收数据 // NSURLConnection回调方法 //如果加载成功就回调 connectionDidFinishLoading:方法 即 请求结束 datas数据完整 //如果加载失败则回调 connection:didFailWithError:方法 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { //不断接受服务器端返回的数据 [self.datas appendData:data]; } //加载数据出现异常 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { //返回一个完整的句子,描述错误的原因 NSLog(@"%@",[error localizedDescription]); } //完成数据加载 -(void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"请求完成"); //josn解析 NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:self.datas options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@",dic); }