网络编程总结

本文转载自http://www.cocoachina.com/bbs/read.php?tid=31300

一:确认网络环境3G/WIFI mm IOgl  
jUj3 'e.p  
    1. 添加源文件和framework "K*iGP  
     Yf ?mEZm  
    开发Web等网络应用程序的时候,需要确认网络环境,连接情况等信息。如果没有处理它们,是不会通过Apple的审查的。 hS(<R!1,i  
    Apple 的 例程 Reachability 中介绍了取得/检测网络状态的方法。要在应用程序程序中使用Reachability,首先要完成如下两部: 8IvI|$[t  
     Dr<JW  
    1.1. 添加源文件: -$)R$I  
    在你的程序中使用 Reachability 只须将该例程中的 Reachability.h 和 Reachability.m 拷贝到你的工程中。如下图: "GT$6,y  
0eOmVQ "6  
     ZLjR-r#   
     u^tLx45  
    1.2.添加framework: }o ]k `  
    将SystemConfiguration.framework 添加进工程。如下图: Fgz.vBK ?B  
     g&j#6?&!{J  
     ^m\{,GL4  
    2. 网络状态 /,U7tY Z  
     'oCtRPn!  
    Reachability.h中定义了三种网络状态: b"K PY>#iw  
    typedef enum { SQP2X< w=l  
        NotReachable = 0,            //无连接 p+QAXU|_1  
        ReachableViaWiFi,            //使用3G/GPRS网络 D!2>:i3,  
        ReachableViaWWAN            //使用WiFi网络  kY%((  
    } NetworkStatus; :5}zh  
     s:#4^Jp'  
    因此可以这样检查网络状态: \4GgcY0/  
|* IZwdS  
    Reachability *r = [Reachability reachabilityWithHostName:@“www.apple.com”]; T_ Et_y|  
    switch ([r currentReachabilityStatus]) { GOM`b;)O  
            case NotReachable: H#.(HFkT-  
                    // 没有网络连接 B#vN`x5  
                    break; i vm Ay  
            case ReachableViaWWAN: -=2=^}  
                    // 使用3G网络 ]srEQ|T)  
                    break; vYh` 6g  
            case ReachableViaWiFi: ?F"c71T  
                    // 使用WiFi网络 JCH]w  
                    break; {|^WA\o -  
    } HBLB_R z:  
     xu1" )h`  
    3.检查当前网络环境 b !qF 1 _  
    程序启动时,如果想检测可用的网络环境,可以像这样 $6T=i x;  
    // 是否wifi 4J! s_a  
    + (BOOL) IsEnableWIFI { 0\=Ooa]  
        return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable); 3pOt.a+uI  
    } /xJJ? p}  
`%2+wQr|  
    // 是否3G cS04$ kjA  
    + (BOOL) IsEnable3G { :?F Zm 2  
        return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable); a?vWEx I$  
    } fa@-|vB=>  
    例子: 38dMu[;X D  
    - (void)viewWillAppear:(BOOL)animated {     nC?jT$>=1  
    if (([Reachability reachabilityForInternetConnection].currentReachabilityStatus == NotReachable) && {- &!B~BB}  
            ([Reachability reachabilityForLocalWiFi].currentReachabilityStatus == NotReachable)) { e(W+ 7Fzx  
            self.navigationItem.hidesBackButton = YES; &gE2xtp`6  
            [self.navigationItem setLeftBarButtonItem:nil animated:NO]; oa=zz (j  
        } 1 AIf9/Z  
    } -~b ,x!  
NN{)^ ~xWo  
    4. 链接状态的实时通知 F;y 8gY   
    网络连接状态的实时检查,通知在网络应用中也是十分必要的。接续状态发生变化时,需要及时地通知用户: $&,J=zosL  
     <NK}{'&T  
    Reachability 1.5版本 uM}Hq"B}  
    // My.AppDelegate.h i_zm _J P,  
    #import "Reachability.h" ZJ z.|+7  
*9>SThX_  
    @interface MyAppDelegate : NSObject <UIApplicationDelegate> { *638r^3nh^  
        NetworkStatus remoteHostStatus; xt7{hAVNj  
    } XCYRwziGO  
~&ZU6YT  
    @property NetworkStatus remoteHostStatus; l^ %0gVK  
6;'Iel m1  
    @end Ab r%wRS  
Q9oXYPLM  
    // My.AppDelegate.m *$oa"~q|M  
    #import "MyAppDelegate.h" >-6 8*QX  
";EoUj|I"  
    @implementation MyAppDelegate Aj7WV'BN  
    @synthesize remoteHostStatus; _@&flgh  
FI1oTM`5  
    // 更新网络状态 pyYlM`*'  
    - (void)updateStatus { *nrJ/  
        self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus]; f%rpS*0uWd  
    } ^u!6X:-  
y/JGS+P@  
    // 通知网络状态 }o ' w*2  
    - (void)reachabilityChanged:(NSNotification *)note { Y^`6'k={9  
        [self updateStatus]; i Jaw\  
        if (self.remoteHostStatus == NotReachable) { v[FJO5y  
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"AppName", nil) ix4r.x;  
                         message:NSLocalizedString (@"NotReachable", nil) DFooZ6wDj  
                        delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; 0:Gs5 qz.G  
            [alert show]; Y O}O[b`#  
            [alert release]; 4L<FY'sa  
        } qrY#~9<!3!  
    } W3f>^n  
Ccz)C&r[!  
    // 程序启动器,启动网络监视 xM=%r  
    - (void)applicationDidFinishLaunching:(UIApplication *)application { mB+,#v{  
     w +?PK)"a  
        // 设置网络检测的站点 ZOnga  
        [[Reachability sharedReachability] setHostName:@"www.apple.com"]; IA@K |!`y8  
        [[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES]; u:UEr x  
        // 设置网络状态变化时的通知函数 k+#d-5 S1  
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) *u] [_o  
                                                 name:@"kNetworkReachabilityChangedNotification" object:nil];  m=\0_B{  
        [self updateStatus]; @Pesto  
    } " :9n|  
yA{>_66  
    - (void)dealloc { QpokXz;#  
        // 删除通知对象 i.lw %/I  
        [[NSNotificationCenter defaultCenter] removeObserver:self]; I/-`;Jy/  
        [window release]; 1:){\"  
        [super dealloc]; j:0| C7  
    } ~<Zb'  
     0Ofl1G  
    Reachability 2.0版本 =[ v47+  
     61iZi{!(  
4[{beh5  
    // MyAppDelegate.h ) *Uq57  
    @class Reachability; -D Tren,  
gKP _Hel  
        @interface MyAppDelegate : NSObject <UIApplicationDelegate> { {RfNUKx  
            Reachability  *hostReach; C7\)4cDe  
        } ~\ 87A7V  
.,}m-VTi\[  
    @end k!wse)6z  
OHu2&&3  
    // MyAppDelegate.m l7n27wmmU  
    - (void)reachabilityChanged:(NSNotification *)note { Owbfx yD  
        Reachability* curReach = [note object]; oxh!\Wv6  
        NSParameterAssert([curReach isKindOfClass: [Reachability class]]); QCG]eR  
        NetworkStatus status = [curReach currentReachabilityStatus]; v$e tQ/_H  
     Fip?h9d9  
        if (status == NotReachable) { <.,mkb  
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"AppName"" f>Z/>V  
                              message:@"NotReachable" ^I!$|u  
                              delegate:nil m^- Md,&*  
                              cancelButtonTitle:@"YES" otherButtonTitles:nil]; >[xGeiw  
                              [alert show]; ^; !lIf3-  
                              [alert release]; ,W{Xs9oI  
        } "B4/[i  
    } q`mu2YMfh  
                               # A yl 3W  
    - (void)applicationDidFinishLaunching:(UIApplication *)application { + &DEy5d  
        // ... Mt=q;xc3  
                   9EJ@EIO5&  
        // 监测网络情况 #k=]%`h  
        [[NSNotificationCenter defaultCenter] addObserver:self QCr}(OOi  
                              selector:@selector(reachabilityChanged:) pNSkF(  
                              name: kReachabilityChangedNotification %WnuZ+Tp  
                              object: nil]; u2S/~HS  
        hostReach = [[Reachability reachabilityWithHostName:@"www.google.com"] retain]; ] &!2%[<v  
        hostReach startNotifer]; (r3I,|UE  
        // ... \L4B)s"" L  
    } g3]2kQU  
U7 &BY.  
>7B9&1 u  
二:使用NSConnection下载数据 9<L'F$lC  
     *4 N  
    1.创建NSConnection对象,设置委托对象 2eNb~|^  
     s"Tc tq8  
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self urlString]]]; R406TkQ  
    [NSURLConnection connectionWithRequest:request delegate:self]; U!L5JOdX`  
     aO'N,NoV{  
    2. NSURLConnection delegate委托方法 g?2G.SBHV  
        - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;   y99aVO"-  
        - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;   *\ZHE)vY  
        - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;   k6C/D12L|  
        - (void)connectionDidFinishLoading:(NSURLConnection *)connection;   CV)BqN?  
\+\}.   
    3. 实现委托方法 #z yT^3B  
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { l{M1 e  
        // store data 0HU5/R{!  
        [self.receivedData setLength:0];            //通常在这里先清空接受数据的缓存 }|Y[cx~R  
    } ,q`YBp_(  
     m\p\q| .  
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { +XUH> Iwz  
           /* appends the new data to the received data */ OhK.rVPH  
        [self.receivedData appendData:data];        //可能多次收到数据,把新的数据添加在现有数据最后 y?WC$  
    }  !6zu~@  
yCB( *  
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 5#e}&^b  
        // 错误处理 aNTUK*J2#  
    } SGA0H  
x7)|GX]  
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection { TU*G[M -'u  
        // disconnect 8,fFZKI  
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;   (N9Kq  
        NSString *returnString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding]; -qjG;`i2Gq  
        NSLog(returnString); SV(-J>u  
        [self urlLoaded:[self urlString] data:self.receivedData]; ZAL-z2O?  
        firstTimeDownloaded = YES; 5e"M D7$  
    } W%a,D{  
5fD[RDi?  
三:使用NSXMLParser解析xml文件 * {'Sta..r  
c{27=Y}SM  
    1. 设置委托对象,开始解析 p`cy"o\  
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];   //或者也可以使用initWithContentsOfURL直接下载文件,但是有一个原因不这么做: 'dg]J4N5  
    // It's also possible to have NSXMLParser download the data, by passing it a URL, but this is not desirable }G?9A)NJp  
    // because it gives less control over the network, particularly in responding to connection errors. ^X!bZ  
    [parser setDelegate:self]; "+: 8  
    [parser parse]; +"XwS:s   
4!15x 9+*)  
    2. 常用的委托方法 }=esb/?Z  
    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName #{ice]XR  
                                namespaceURI:(NSString *)namespaceURI aBD7 3g  
                                qualifiedName:(NSString *)qName AXxY*f  
                                attributes:(NSDictionary *)attributeDict; ycN[_CW  
    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName {k0SN,P%  
                                namespaceURI:(NSString *)namespaceURI +z [siwz;Y  
                                qualifiedName:(NSString *)qName; ^BM@ufBR  
    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string; )AElec<HI  
    - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError; k* [Q  
Q7J 7.d  
    static NSString *feedURLString = @"http://www.yifeiyang.net/test/test.xml"; z>uu~!WoRM  
+[6'J{Yi  
    3.  应用举例 Ux|=}A-+D  
    - (void)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error w?0:ae\  
    { G-TqPAwGO  
        NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:URL]; !!=v,88G  
        [parser setDelegate:self]; MB\dUZFoT  
        [parser setShouldProcessNamespaces:NO]; AQAo!B}  
        [parser setShouldReportNamespacePrefixes:NO]; p+1 @ VC$  
        [parser setShouldResolveExternalEntities:NO]; X?\# (a  
        [parser parse]; sQ#% }  
        NSError *parseError = [parser parserError]; \WgwH.ou  
        if (parseError && error) { 6 %k 7B  
            *error = parseError;  #9 k-Vt5  
        } kNlk"5ZE-`  
        [parser release]; wsni85  
    } .;XR4  
-[sCYtUy  
    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI LL0 fP$2=  
                                        qualifiedName:(NSString*)qName attributes:(NSDictionary *)attributeDict{ QNZn)x  
        // 元素开始句柄 lFfs6"dW  
        if (qName) { V(]B:7L  
            elementName = qName; N3M 4i:  
        } )EHvc8NJ  
        if ([elementName isEqualToString:@"user"]) { )H6n-|y(TK  
            // 输出属性值 |1svdz]_z  
            NSLog(@"Name is %@ , Age is %@", [attributeDict objectForKey:@"name"], [attributeDict objectForKey:@"age"]); i +Z_?V  
        } Q ? A?Fr  
    } @R`iKTx)3  
^93wJ&/I  
    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI p~sfOpZ  
                                        qualifiedName:(NSString *)qName dFKk&}yR_  
    { <PW[}E]B  
        // 元素终了句柄 MMhY(JD  
        if (qName) { { 5!`F| A@  
               elementName = qName; qz:;H'BC  
        } O@iYKo/B  
    } id)Ga0N  
8{y cgHs  
    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 8*#W}m8  
    { =-E]Sr;g  
        // 取得元素的text [lpU."!  
    } IDGbMWV1  
<H/)k-  
    NSError *parseError = nil; cSuF'{/(Q  
    [self parseXMLFileAtURL:[NSURL URLWithString:feedURLString] parseError:&parseError]; `$&/nLD|cF  

原文地址:https://www.cnblogs.com/gaoxiao228/p/2794277.html