아이폰어플개발정보2010. 10. 12. 04:03
아이폰 어플개발할때 Wifi,3G연결 체크하는 소스

Usage is really simple:

  1. if ([Connection isConnected]) {  ...  }  
  2. else {  ...  }  

Connection.m file:

  1. //
  2. //  Connection.m
  3. //  iBlog
  4. //
  5. //  Created by Ondrej Rafaj on 12.11.09.
  6. //  Copyright 2009 Home. All rights reserved.
  7. //
  8. #import "Connection.h"
  9. @implementation Connection  
  10. + (BOOL) isConnected {  
  11.     // Create zero addy
  12.     struct sockaddr_in zeroAddress;  
  13.     bzero(&zeroAddress, sizeof(zeroAddress));  
  14.     zeroAddress.sin_len = sizeof(zeroAddress);  
  15.     zeroAddress.sin_family = AF_INET;  
  16.     // Recover reachability flags
  17.     SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);  
  18.     SCNetworkReachabilityFlags flags;  
  19.     BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);  
  20.     CFRelease(defaultRouteReachability);  
  21.     if (!didRetrieveFlags) {  
  22.         NSLog(@"Error. Could not recover network reachability flags");  
  23.         return NO;  
  24.     }  
  25.     BOOL isReachable = flags & kSCNetworkFlagsReachable;  
  26.     BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;  
  27.     BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;  
  28.     NSURL *testURL = [NSURL URLWithString:@"http://www.google.com/"];  
  29.     NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL  cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];  
  30.     NSURLConnection *testConnection = [[[NSURLConnection alloc] initWithRequest:testRequest delegate:self] autorelease];  
  31.     return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO;  
  32. }  
  33. @end  

And this is the header Connection.h file:

  1. //
  2. //  Connection.h
  3. //  iBlog
  4. // 
  5. //  Created by Ondrej Rafaj on 12.11.09.
  6. //  Copyright 2009 Home. All rights reserved.
  7. //
  8. #import 
  9. #import 
  10. #import 
  11. #import 
  12. #import 
  13. @interface Connection : NSObject {  
  14. }  
  15. + (BOOL) isConnected;  
  16. @end  

And don't forget to include all the necessary frameworks ;) ... SystemConfiguration and libz.1.1.3.dylib

Ondrej Rafaj

Independent iPhone developer @ ondrej-rafaj.co.uk

I am available to give you a free quote or start working on your project ... just give me a call or drop a line. Please find all my details on my portfolio site ondrej-rafaj.co.uk

http://www.xprogress.com/post-40-iphone-internet-connection-check-wifi-3g-edge-something-like-reachability-h/

Posted by 오늘마감

댓글을 달아 주세요