终于算埋头把ios开发啃下来,慢慢的也算来了感觉,不会像开始那样束手无策;先给看看写的demo吧:
一个访问网络的并取得数据的demo:UI就不说了 一个UITextField和一个UIButton。。。给按钮绑定一个访问网络的事件,其中会从text那边接受部分参数;
-(void)loadURL
{
NSString *urlstart=@"http://76.74.172.237:8080/WowServer/wowandroid?pid=1&q=";
NSString *urlstring =[NSString stringWithFormat:@"%@%@",urlstart,namefield.text ];
//转换编码,不然namefield.text接受来的中文字符不能识别,NSURL就不能初始成功;
urlstring = [urlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlstring];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
//[webView loadRequest:request];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(connection)
{
receivedData = [[NSMutableData data] retain];
NSLog(@"intial done!");
}
else
{
NSLog(@"sorry");
}
[urlstart release];
[connection release];
[request release];
[url release];
}
NSURLConnection是个异步请求网络的方法,必须实现的方法有这几个
//表示已经收到足够多组成NSURLRespone的内容了
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response
{
NSLog(@"get the whole response");
[receivedData setLength:0];
}
//提供一个NSData,封装了从连接上收到的字节
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"get some data");
[receivedData appendData:data];
}
// 下载完成了,可以处置这些字节了
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *str=[[NSString alloc] initWithData: receivedData encoding:NSUTF8StringEncoding];
NSLog(@"str%@",str);
[str release];
[receivedData release];
}
//如果下载失败了,解释原因
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Connection failed! Error ");
}