iPhone网络开发 小结

一、确认网络环境3G/WIFI

  1. 添加源文件framework

开发Web等网络应用程序的时候,需要确认网络环境,连接情况等信息。如果没有处理它们,是不会通过Apple的审查的。Apple 的 例程 Reachability 中介绍了取得检测网络状态的方法。要在应用程序程序中使用Reachability,首先要完成如下两部:

1.1. 添加源文件:

  在你的程序中使用 Reachability 只须将该例程中的 Reachability.h 和 Reachability.m 拷贝到你的工程中。如下图:

1.2.添加framework:

将SystemConfiguration.framework 添加进工程。如下图:

2、网络状态

Reachability.h中定义了三种网络状态:

 
  1. typedefenum{
  2. NotReachable=0,//无连接
  3. ReachableViaWiFi,//使用3G/GPRS网络
  4. ReachableViaWWAN//使用WiFi网络
  5. }NetworkStatus;
  6. 这样检查网络状态:
  7. Reachability*r=[ReachabilityreachabilityWithHostName:@“www.apple.com”];
  8. switch([rcurrentReachabilityStatus]){
  9. caseNotReachable:
  10. //没有网络连接
  11. break;
  12. caseReachableViaWWAN:
  13. //使用3G网络
  14. break;
  15. caseReachableViaWiFi:
  16. //使用WiFi网络
  17. break;
  18. }

  3.检查当前网络环境

  程序启动时,如果想检测可用的网络环境,可以像这样

 
  1. //是否wifi
  2. +(BOOL)IsEnableWIFI{
  3. return([[ReachabilityreachabilityForLocalWiFi]currentReachabilityStatus]!=NotReachable);
  4. }
  5. //是否3G
  6. +(BOOL)IsEnable3G{
  7. return([[ReachabilityreachabilityForInternetConnection]currentReachabilityStatus]!=NotReachable);
  8. }
  9. 例子:
  10. -(void)viewWillAppear:(BOOL)animated{
  11. if(([ReachabilityreachabilityForInternetConnection].currentReachabilityStatus==NotReachable)&&
  12. ([ReachabilityreachabilityForLocalWiFi].currentReachabilityStatus==NotReachable)){
  13. self.navigationItem.hidesBackButton=YES;
  14. [self.navigationItemsetLeftBarButtonItem:nilanimated:NO];
  15. }
  16. }

  4、链接状态的实时通知

  网络连接状态的实时检查,通知在网络应用中也是十分必要的。接续状态发生变化时,需要及时地通知用户

Reachability 1.5版本

 
  1. //My.AppDelegate.h
  2. #import"Reachability.h"
  3. @interfaceMyAppDelegate:NSObject<UIApplicationDelegate>{
  4. NetworkStatusremoteHostStatus;
  5. }
  6. @propertyNetworkStatusremoteHostStatus;
  7. @end
  8. //My.AppDelegate.m
  9. #import"MyAppDelegate.h"
  10. @implementationMyAppDelegate
  11. @synthesizeremoteHostStatus;
  12. //更新网络状态
  13. -(void)updateStatus{
  14. self.remoteHostStatus=[[ReachabilitysharedReachability]remoteHostStatus];
  15. }
  16. //通知网络状态
  17. -(void)reachabilityChanged:(NSNotification*)note{
  18. [selfupdateStatus];
  19. if(self.remoteHostStatus==NotReachable){
  20. UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:NSLocalizedString(@"AppName",nil)
  21. message:NSLocalizedString(@"NotReachable",nil)
  22. delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil];
  23. [alertshow];
  24. [alertrelease];
  25. }
  26. }
  27. //程序启动器,启动网络监视
  28. -(void)applicationDidFinishLaunching:(UIApplication*)application{
  29. //设置网络检测的站点
  30. [[ReachabilitysharedReachability]setHostName:@"www.apple.com"];
  31. [[ReachabilitysharedReachability]setNetworkStatusNotificationsEnabled:YES];
  32. //设置网络状态变化时的通知函数
  33. [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(reachabilityChanged:)
  34. name:@"kNetworkReachabilityChangedNotification"object:nil];
  35. [selfupdateStatus];
  36. }
  37. -(void)dealloc{
  38. //删除通知对象
  39. [[NSNotificationCenterdefaultCenter]removeObserver:self];
  40. [windowrelease];
  41. [superdealloc];
  42. }
  43. Reachability2.0版本
  44. //MyAppDelegate.h
  45. @classReachability;
  46. @interfaceMyAppDelegate:NSObject<UIApplicationDelegate>{
  47. Reachability*hostReach;
  48. }
  49. @end
  50. //MyAppDelegate.m
  51. -(void)reachabilityChanged:(NSNotification*)note{
  52. Reachability*curReach=[noteobject];
  53. NSParameterAssert([curReachisKindOfClass:[Reachabilityclass]]);
  54. NetworkStatusstatus=[curReachcurrentReachabilityStatus];
  55. if(status==NotReachable){
  56. UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:@"AppName""
  57. message:@"NotReachable"
  58. delegate:nil
  59. cancelButtonTitle:@"YES"otherButtonTitles:nil];
  60. [alertshow];
  61. [alertrelease];
  62. }
  63. }
  64. -(void)applicationDidFinishLaunching:(UIApplication*)application{
  65. //...
  66. //监测网络情况
  67. [[NSNotificationCenterdefaultCenter]addObserver:self
  68. selector:@selector(reachabilityChanged:)
  69. name:kReachabilityChangedNotification
  70. object:nil];
  71. hostReach=[[ReachabilityreachabilityWithHostName:@"www.google.com"]retain];
  72. hostReachstartNotifer];
  73. //...
  74. }

  二、使用NSConnection下载数据

  1、创建NSConnection对象,设置委托对象

 
  1. NSMutableURLRequest*request=[NSMutableURLRequestrequestWithURL:[NSURLURLWithString:[selfurlString]]];
  2. [NSURLConnectionconnectionWithRequest:requestdelegate:self];

  2、NSURLConnection delegate委托方法

 
  1. -(void)connection:(NSURLConnection*)connectiondidReceiveResponse:(NSURLResponse*)response;
  2. -(void)connection:(NSURLConnection*)connectiondidFailWithError:(NSError*)error;
  3. -(void)connection:(NSURLConnection*)connectiondidReceiveData:(NSData*)data;
  4. -(void)connectionDidFinishLoading:(NSURLConnection*)connection;

  3. 实现委托方法

 
  1. -(void)connection:(NSURLConnection*)connectiondidReceiveResponse:(NSURLResponse*)response{
  2. //storedata
  3. [self.receivedDatasetLength:0];//通常在这里先清空接受数据的缓存
  4. }
  5. -(void)connection:(NSURLConnection*)connectiondidReceiveData:(NSData*)data{
  6. [self.receivedDataappendData:data];//可能多次收到数据,把新的数据添加在现有数据最后
  7. }
  8. -(void)connection:(NSURLConnection*)connectiondidFailWithError:(NSError*)error{
  9. //错误处理
  10. }
  11. -(void)connectionDidFinishLoading:(NSURLConnection*)connection{
  12. //disconnect
  13. [UIApplicationsharedApplication].networkActivityIndicatorVisible=NO;
  14. NSString*returnString=[[NSStringalloc]initWithData:self.receivedDataencoding:NSUTF8StringEncoding];
  15. NSLog(returnString);
  16. [selfurlLoaded:[selfurlString]data:self.receivedData];
  17. firstTimeDownloaded=YES;
  18. }

  三、使用NSXMLParser解析xml文件

  1. 设置委托对象,开始解析

 
  1. NSXMLParser*parser=[[NSXMLParseralloc]initWithData:data];//或者也可以使用initWithContentsOfURL直接下载文件,但是有一个原因不这么做:
  2. //ItsalsopossibletohaveNSXMLParserdownloadthedata,bypassingitaURL,butthisisnotdesirable
  3. //becauseitgiveslesscontroloverthenetwork,particularlyinrespondingtoconnectionerrors.
  4. [parsersetDelegate:self];
  5. [parserparse];

  2. 常用的委托方法

 
  1. -(void)parser:(NSXMLParser*)parserdidStartElement:(NSString*)elementName
  2. namespaceURI:(NSString*)namespaceURI
  3. qualifiedName:(NSString*)qName
  4. attributes:(NSDictionary*)attributeDict;
  5. -(void)parser:(NSXMLParser*)parserdidEndElement:(NSString*)elementName
  6. namespaceURI:(NSString*)namespaceURI
  7. qualifiedName:(NSString*)qName;
  8. -(void)parser:(NSXMLParser*)parserfoundCharacters:(NSString*)string;
  9. -(void)parser:(NSXMLParser*)parserparseErrorOccurred:(NSError*)parseError;
  10. staticNSString*feedURLString=@"http://www.yifeiyang.net/test/test.xml";

  3. 应用举例

 
  1. -(void)parseXMLFileAtURL:(NSURL*)URLparseError:(NSError**)error
  2. {
  3. NSXMLParser*parser=[[NSXMLParseralloc]initWithContentsOfURL:URL];
  4. [parsersetDelegate:self];
  5. [parsersetShouldProcessNamespaces:NO];
  6. [parsersetShouldReportNamespacePrefixes:NO];
  7. [parsersetShouldResolveExternalEntities:NO];
  8. [parserparse];
  9. NSError*parseError=[parserparserError];
  10. if(parseError&&error){
  11. *error=parseError;
  12. }
  13. [parserrelease];
  14. }
  15. -(void)parser:(NSXMLParser*)parserdidStartElement:(NSString*)elementNamenamespaceURI:(NSString*)namespaceURI
  16. qualifiedName:(NSString*)qNameattributes:(NSDictionary*)attributeDict{
  17. //元素开始句柄
  18. if(qName){
  19. elementName=qName;
  20. }
  21. if([elementNameisEqualToString:@"user"]){
  22. //输出属性
  23. NSLog(@"Nameis%@,Ageis%@",[attributeDictobjectForKey:@"name"],[attributeDictobjectForKey:@"age"]);
  24. }
  25. }
  26. -(void)parser:(NSXMLParser*)parserdidEndElement:(NSString*)elementNamenamespaceURI:(NSString*)namespaceURI
  27. qualifiedName:(NSString*)qName
  28. {
  29. //元素终了句柄
  30. if(qName){
  31. elementName=qName;
  32. }
  33. }
  34. -(void)parser:(NSXMLParser*)parserfoundCharacters:(NSString*)string
  35. {
  36. //取得元素的text
  37. }
  38. NSError*parseError=nil;
  39. [selfparseXMLFileAtURL:[NSURLURLWithString:feedURLString]parseError:&parseError];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值