我正在开发一个从网络服务器获取 JSON 数据的 iphone 应用程序,并且我正在使用 NSURLConnectionDelegate、NSURLConnectionDataDelegate、NSURLConnectionDownloadDelegate 协议。我能够使用 localhost 成功获取数据,但无法从 Internet Web 服务器获取数据。
NSURL*url=[NSURL URLWithString:urlString];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSLog(@"%@",theRequest);
// Create the connection with the request and start loading the data.
// NSURLDownload *theDownload = [[NSURLDownload alloc] initWithRequest:Request delegate:self];
NSURLConnection* connection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
其他委托方法如下
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
mydata =[[NSMutableData alloc] init];
[mydata setLength:0];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView*errorView =[[UIAlertView alloc] initWithTitle:@"Error" message:@"The download could not be completed- please make sure you are connected to Internet either 3G or Wi-fi" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
[errorView show];
}
-(void)connectionDidFinishLoading:(NSURLConnection*)connection{
NSArray*jsonArr =[[NSArray alloc] init];
NSError*error;
jsonArr= [NSJSONSerialization JSONObjectWithData:mydata options:NSJSONReadingAllowFragments error:&error];
NSLog(@"%@",error);
NSLog(@"Json Array %@",jsonArr);
self.questions = [NSMutableArray arrayWithArray:jsonArr];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
我收到此错误:错误域 = NSCocoaErrorDomain 代码 = 3840“操作无法完成。(可可错误 3840。)”(字符 3 周围的值无效。) UserInfo = 0x71be760 {NSDebugDescription = 字符 3 周围的值无效。}
仅在尝试来自 Internet 网络服务器的数据时出现,并且在访问 localhost 时不会出现
All the code works perfectly if I use url as http://localhost/example.php but as soon as
I change the url to use the web server url http://www.example.net/data.php
although there is no problem with connection but it returns data as nil.
任何建议表示赞赏!