diff --git a/Classes/FlickrKit.h b/Classes/FlickrKit.h index 846d8c0..274af67 100644 --- a/Classes/FlickrKit.h +++ b/Classes/FlickrKit.h @@ -128,10 +128,13 @@ FOUNDATION_EXPORT const unsigned char FlickrKitVersionString[]; - (FKDUNetworkOperation *) beginAuthWithCallbackURL:(NSURL *)url permission:(FKPermission)permission completion:(FKAPIAuthBeginCompletion)completion; // 2. After they login and authorize the app, need to get an auth token - this will happen via your URL scheme - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url - (FKDUNetworkOperation *) completeAuthWithURL:(NSURL *)url completion:(FKAPIAuthCompletion)completion; +- (FKDUNetworkOperation *) completeAuthWithURL:(NSURL *)url saveAuthTokenToUserDefaults:(BOOL)persistAuthToken completion:(FKAPIAuthCompletion)completion; // 3. On returning to the app, you want to re-log them in automatically - do it here - (FKFlickrNetworkOperation *) checkAuthorizationOnCompletion:(FKAPIAuthCompletion)completion; // 4. Logout - just removes all the stored keys - (void) logout; +// 5. Programatic Login - allow logging in with supplied tokens +- (void) loginWithAuthToken:(NSString *)authToken authSecret:(NSString *)authSecret; @end diff --git a/Classes/FlickrKit/FlickrKit.m b/Classes/FlickrKit/FlickrKit.m index dc574d5..77875e1 100644 --- a/Classes/FlickrKit/FlickrKit.m +++ b/Classes/FlickrKit/FlickrKit.m @@ -59,11 +59,11 @@ - (FKFlickrNetworkOperation *) call:(NSString *)apiMethod args:(NSDictionary *)r } - (FKFlickrNetworkOperation *) call:(NSString *)apiMethod args:(NSDictionary *)requestArgs maxCacheAge:(FKDUMaxAge)maxAge completion:(FKAPIRequestCompletion)completion { - NSAssert([FlickrKit sharedFlickrKit].apiKey, @"You must pass an apiKey to initializeWithAPIKey"); + NSAssert(self.apiKey, @"You must pass an apiKey to initializeWithAPIKey"); NSAssert(apiMethod, @"You must pass an apiMethod"); NSAssert(completion, @"You must pass a completion block"); - if ([FKDUReachability isOffline]) { + if ([FKDUReachability isOffline]) { if (completion) { completion(nil, [FKDUReachability buildOfflineErrorMessage]); } @@ -74,7 +74,7 @@ - (FKFlickrNetworkOperation *) call:(NSString *)apiMethod args:(NSDictionary *)r self.diskCache = [FKDUDefaultDiskCache sharedDiskCache]; } - FKFlickrNetworkOperation *op = [[FKFlickrNetworkOperation alloc] initWithAPIMethod:apiMethod arguments:requestArgs maxAgeMinutes:maxAge diskCache:self.diskCache completion:completion]; + FKFlickrNetworkOperation *op = [[FKFlickrNetworkOperation alloc] initWithFlickrKit:self APIMethod:apiMethod arguments:requestArgs maxAgeMinutes:maxAge completion:completion]; [[FKDUNetworkController sharedController] execute:op]; return op; @@ -87,12 +87,12 @@ - (FKFlickrNetworkOperation *) call:(id)method completion:(FK } - (FKFlickrNetworkOperation *) call:(id)method maxCacheAge:(FKDUMaxAge)maxAge completion:(FKAPIRequestCompletion)completion { - NSAssert([FlickrKit sharedFlickrKit].apiKey, @"You must pass an apiKey to initializeWithAPIKey"); + NSAssert(self.apiKey, @"You must pass an apiKey to initializeWithAPIKey"); NSAssert(method, @"You must pass a method"); // Check if this method needs auth if ([method needsLogin]) { - if (![FlickrKit sharedFlickrKit].isAuthorized) { + if (!self.isAuthorized) { NSString *errorDescription = @"You need to login to call this method"; NSDictionary *userInfo = @{NSLocalizedDescriptionKey: errorDescription}; NSError *error = [NSError errorWithDomain:FKFlickrAPIErrorDomain code:FKErrorNotAuthorized userInfo:userInfo]; @@ -101,7 +101,7 @@ - (FKFlickrNetworkOperation *) call:(id)method maxCacheAge:(F } else { // Check method permission FKPermission permissionRequired = [method requiredPerms]; - FKPermission grantedPermission = [FlickrKit sharedFlickrKit].permissionGranted; + FKPermission grantedPermission = self.permissionGranted; if (permissionRequired > grantedPermission) { NSString *requiredString = FKPermissionStringForPermission(permissionRequired); NSString *grantedString = FKPermissionStringForPermission(grantedPermission); @@ -126,7 +126,7 @@ - (FKFlickrNetworkOperation *) call:(id)method maxCacheAge:(F self.diskCache = [FKDUDefaultDiskCache sharedDiskCache]; } - FKFlickrNetworkOperation *op = [[FKFlickrNetworkOperation alloc] initWithAPIMethod:method maxAgeMinutes:maxAge diskCache:self.diskCache completion:completion]; + FKFlickrNetworkOperation *op = [[FKFlickrNetworkOperation alloc] initWithFlickrKit:self APIMethod:method maxAgeMinutes:maxAge completion:completion]; [[FKDUNetworkController sharedController] execute:op]; return op; @@ -198,7 +198,7 @@ - (FKDUNetworkOperation *) beginAuthWithCallbackURL:(NSURL *)url permission:(FKP } NSDictionary *paramsDictionary = @{@"oauth_callback": [url absoluteString]}; - FKURLBuilder *urlBuilder = [[FKURLBuilder alloc] init]; + FKURLBuilder *urlBuilder = [[FKURLBuilder alloc] initWithFlickrKit:self]; NSURL *requestURL = [urlBuilder oauthURLFromBaseURL:[NSURL URLWithString:@"https://www.flickr.com/services/oauth/request_token"] method:FKHttpMethodGET params:paramsDictionary]; FKDUNetworkOperation *op = [[FKDUNetworkOperation alloc] initWithURL:requestURL]; @@ -235,6 +235,11 @@ - (FKDUNetworkOperation *) beginAuthWithCallbackURL:(NSURL *)url permission:(FKP } - (FKDUNetworkOperation *) completeAuthWithURL:(NSURL *)url completion:(FKAPIAuthCompletion)completion { + // By default persist token to user defaults + return [self completeAuthWithURL:url saveAuthTokenToUserDefaults:YES completion:completion]; +} + +- (FKDUNetworkOperation *) completeAuthWithURL:(NSURL *)url saveAuthTokenToUserDefaults:(BOOL)persistAuthToken completion:(FKAPIAuthCompletion)completion { if ([FKDUReachability isOffline]) { if (completion) { @@ -258,7 +263,7 @@ - (FKDUNetworkOperation *) completeAuthWithURL:(NSURL *)url completion:(FKAPIAut } NSDictionary *paramsDictionary = @{@"oauth_token": token, @"oauth_verifier": verifier}; - FKURLBuilder *urlBuilder = [[FKURLBuilder alloc] init]; + FKURLBuilder *urlBuilder = [[FKURLBuilder alloc] initWithFlickrKit:self]; NSURL *requestURL = [urlBuilder oauthURLFromBaseURL:[NSURL URLWithString:@"https://www.flickr.com/services/oauth/access_token"] method:FKHttpMethodGET params:paramsDictionary]; FKDUNetworkOperation *op = [[FKDUNetworkOperation alloc] initWithURL:requestURL]; @@ -294,9 +299,11 @@ - (FKDUNetworkOperation *) completeAuthWithURL:(NSURL *)url completion:(FKAPIAut completion(nil, nil, nil, error); } } else { - [[NSUserDefaults standardUserDefaults] setValue:oat forKey:kFKStoredTokenKey]; - [[NSUserDefaults standardUserDefaults] setValue:oats forKey:kFKStoredTokenSecret]; - [[NSUserDefaults standardUserDefaults] synchronize]; + if (persistAuthToken) { + [[NSUserDefaults standardUserDefaults] setValue:oat forKey:kFKStoredTokenKey]; + [[NSUserDefaults standardUserDefaults] setValue:oats forKey:kFKStoredTokenSecret]; + [[NSUserDefaults standardUserDefaults] synchronize]; + } self.authorized = YES; self.authToken = oat; self.authSecret = oats; @@ -384,6 +391,14 @@ - (void) logout { self.beginAuthURL = nil; } +#pragma mark - 5. Programatic Login - allow logging in with supplied tokens + +- (void) loginWithAuthToken:(NSString *)authToken authSecret:(NSString *)authSecret { + self.authorized = YES; + self.authToken = authToken; + self.authSecret = authSecret; +} + @end @@ -452,16 +467,17 @@ - (NSURL *) photoURLForSize:(FKPhotoSize)size photoID:(NSString *)photoID server @implementation FlickrKit (PhotoUpload) - (FKImageUploadNetworkOperation *) uploadImage:(DUImage *)image args:(NSDictionary *)args completion:(FKAPIImageUploadCompletion)completion { - FKImageUploadNetworkOperation *imageUpload = [[FKImageUploadNetworkOperation alloc] initWithImage:image arguments:args completion:completion]; + FKImageUploadNetworkOperation *imageUpload = [[FKImageUploadNetworkOperation alloc] initWithFlickrKit:self image:image arguments:args completion:completion]; [[FKDUNetworkController sharedController] execute:imageUpload]; return imageUpload; } #if TARGET_OS_IOS - (FKImageUploadNetworkOperation *) uploadAssetURL:(NSURL *)assetURL args:(NSDictionary *)args completion:(FKAPIImageUploadCompletion)completion { - FKImageUploadNetworkOperation *imageUpload = [[FKImageUploadNetworkOperation alloc] initWithAssetURL:assetURL - arguments:args - completion:completion]; + FKImageUploadNetworkOperation *imageUpload = [[FKImageUploadNetworkOperation alloc] initWithFlickrKit:self + assetURL:assetURL + arguments:args + completion:completion]; [[FKDUNetworkController sharedController] execute:imageUpload]; return imageUpload; } diff --git a/Classes/Network/FKFlickrNetworkOperation.h b/Classes/Network/FKFlickrNetworkOperation.h index 34e3ca9..3b667e2 100644 --- a/Classes/Network/FKFlickrNetworkOperation.h +++ b/Classes/Network/FKFlickrNetworkOperation.h @@ -6,6 +6,8 @@ // Copyright (c) 2013 DevedUp Ltd. All rights reserved. http://www.devedup.com // +@class FlickrKit; + #import "FKDataTypes.h" #import "FKDUConcurrentOperation.h" #import "FKDUDiskCache.h" @@ -14,8 +16,7 @@ @interface FKFlickrNetworkOperation : FKDUNetworkOperation -- (id) initWithAPIMethod:(NSString *)api arguments:(NSDictionary *)args maxAgeMinutes:(FKDUMaxAge)maxAge diskCache:(id)diskCache completion:(FKAPIRequestCompletion)completion; - -- (id) initWithAPIMethod:(id)method maxAgeMinutes:(FKDUMaxAge)maxAge diskCache:(id)diskCache completion:(FKAPIRequestCompletion)completion; +- (id) initWithFlickrKit:(FlickrKit *)flickrKit APIMethod:(NSString *)api arguments:(NSDictionary *)args maxAgeMinutes:(FKDUMaxAge)maxAge completion:(FKAPIRequestCompletion)completion; +- (id) initWithFlickrKit:(FlickrKit *)flickrKit APIMethod:(id)method maxAgeMinutes:(FKDUMaxAge)maxAge completion:(FKAPIRequestCompletion)completion; @end diff --git a/Classes/Network/FKFlickrNetworkOperation.m b/Classes/Network/FKFlickrNetworkOperation.m index dd41335..288bb73 100644 --- a/Classes/Network/FKFlickrNetworkOperation.m +++ b/Classes/Network/FKFlickrNetworkOperation.m @@ -14,10 +14,10 @@ #import "FKDUNetworkController.h" @interface FKFlickrNetworkOperation () +@property (nonatomic, strong) FlickrKit *flickrKit; @property (nonatomic, strong) NSString *apiMethod; @property (nonatomic, strong) NSDictionary *args; @property (nonatomic, copy) FKAPIRequestCompletion completion; -@property (nonatomic, strong) id diskCache; @property (nonatomic, assign) NSInteger maxAgeMinutes; @property (nonatomic, strong) NSString *cacheKey; @property (nonatomic, retain) id method; @@ -28,11 +28,11 @@ @implementation FKFlickrNetworkOperation #pragma mark - Init -- (id) initWithAPIMethod:(NSString *)api arguments:(NSDictionary *)args maxAgeMinutes:(FKDUMaxAge)maxAge diskCache:(id)diskCache completion:(FKAPIRequestCompletion)completion { +- (id) initWithFlickrKit:(FlickrKit *)flickrKit APIMethod:(NSString *)api arguments:(NSDictionary *)args maxAgeMinutes:(FKDUMaxAge)maxAge completion:(FKAPIRequestCompletion)completion { self = [super init]; if (self) { + self.flickrKit = flickrKit; self.maxAgeMinutes = maxAge; - self.diskCache = diskCache; self.apiMethod = api; self.args = args; self.completion = completion; @@ -42,10 +42,10 @@ - (id) initWithAPIMethod:(NSString *)api arguments:(NSDictionary *)args maxAgeMi return self; } -- (id) initWithAPIMethod:(id)method maxAgeMinutes:(FKDUMaxAge)maxAge diskCache:(id)diskCache completion:(FKAPIRequestCompletion)completion { +- (id) initWithFlickrKit:(FlickrKit *)flickrKit APIMethod:(id)method maxAgeMinutes:(FKDUMaxAge)maxAge completion:(FKAPIRequestCompletion)completion { NSString *api = [method name]; NSDictionary *args = [method args]; - return [self initWithAPIMethod:api arguments:args maxAgeMinutes:maxAge diskCache:diskCache completion:completion]; + return [self initWithFlickrKit:flickrKit APIMethod:api arguments:args maxAgeMinutes:maxAge completion:completion]; } #pragma mark - DUOperation Methods @@ -71,9 +71,9 @@ - (BOOL) startRequest:(NSError **)error { NSData *cachedData = nil; if (0 == self.maxAgeMinutes) { - [self.diskCache removeDataForKey:self.cacheKey]; + [self.flickrKit.diskCache removeDataForKey:self.cacheKey]; } else { - cachedData = [self.diskCache dataForKey:self.cacheKey maxAgeMinutes:self.maxAgeMinutes]; + cachedData = [self.flickrKit.diskCache dataForKey:self.cacheKey maxAgeMinutes:self.maxAgeMinutes]; } if (cachedData) { @@ -133,7 +133,7 @@ - (void) connectionDidFinishLoading:(NSURLConnection *)connection { //Cache the response if (data && data.length > 0) { if (0 != self.maxAgeMinutes) { - [self.diskCache storeData:subData forKey:self.cacheKey]; + [self.flickrKit.diskCache storeData:subData forKey:self.cacheKey]; } [self processResponseData:subData]; } else { @@ -156,10 +156,10 @@ - (NSMutableURLRequest *) createRequest:(NSError **)error { newArgs[@"method"] = self.apiMethod; newArgs[@"format"] = @"json"; - FKURLBuilder *urlBuilder = [[FKURLBuilder alloc] init]; + FKURLBuilder *urlBuilder = [[FKURLBuilder alloc] initWithFlickrKit:self.flickrKit]; NSURL *url = nil; - if ([FlickrKit sharedFlickrKit].isAuthorized) { + if (self.flickrKit.isAuthorized) { url = [urlBuilder oauthURLFromBaseURL:[NSURL URLWithString:FKFlickrRESTAPI] method:FKHttpMethodGET params:newArgs]; } else { NSString *query = [urlBuilder signedQueryStringFromParameters:newArgs]; diff --git a/Classes/Network/FKImageUploadNetworkOperation.h b/Classes/Network/FKImageUploadNetworkOperation.h index 531c162..7e7ede6 100644 --- a/Classes/Network/FKImageUploadNetworkOperation.h +++ b/Classes/Network/FKImageUploadNetworkOperation.h @@ -9,13 +9,15 @@ #import "FKDUNetworkOperation.h" #import "FKDataTypes.h" +@class FlickrKit; + @interface FKImageUploadNetworkOperation : FKDUNetworkOperation @property (nonatomic, assign, readonly) CGFloat uploadProgress; -- (id) initWithImage:(DUImage *)image arguments:(NSDictionary *)args completion:(FKAPIImageUploadCompletion)completion; +- (id) initWithFlickrKit:(FlickrKit *)flickrKit image:(DUImage *)image arguments:(NSDictionary *)args completion:(FKAPIImageUploadCompletion)completion; #if TARGET_OS_IOS -- (id) initWithAssetURL:(NSURL *)assetURL arguments:(NSDictionary *)args completion:(FKAPIImageUploadCompletion)completion; +- (id) initWithFlickrKit:(FlickrKit *)flickrKit assetURL:(NSURL *)assetURL arguments:(NSDictionary *)args completion:(FKAPIImageUploadCompletion)completion; #endif @end diff --git a/Classes/Network/FKImageUploadNetworkOperation.m b/Classes/Network/FKImageUploadNetworkOperation.m index 90364e4..9cddfce 100644 --- a/Classes/Network/FKImageUploadNetworkOperation.m +++ b/Classes/Network/FKImageUploadNetworkOperation.m @@ -15,6 +15,7 @@ @interface FKImageUploadNetworkOperation () +@property (nonatomic, strong) FlickrKit *flickrKit; @property (nonatomic, strong) DUImage *image; @property (nonatomic, retain) NSString *tempFile; @property (nonatomic, copy) FKAPIImageUploadCompletion completion; @@ -28,9 +29,10 @@ @interface FKImageUploadNetworkOperation () @implementation FKImageUploadNetworkOperation -- (id) initWithImage:(DUImage *)image arguments:(NSDictionary *)args completion:(FKAPIImageUploadCompletion)completion; { +- (id) initWithFlickrKit:(FlickrKit *)flickrKit image:(DUImage *)image arguments:(NSDictionary *)args completion:(FKAPIImageUploadCompletion)completion; { self = [super init]; if (self) { + self.flickrKit = flickrKit; self.image = image; self.args = args; self.completion = completion; @@ -39,9 +41,10 @@ - (id) initWithImage:(DUImage *)image arguments:(NSDictionary *)args completion: } #if TARGET_OS_IOS -- (id) initWithAssetURL:(NSURL *)assetURL arguments:(NSDictionary *)args completion:(FKAPIImageUploadCompletion)completion; { +- (id) initWithFlickrKit:(FlickrKit *)flickrKit assetURL:(NSURL *)assetURL arguments:(NSDictionary *)args completion:(FKAPIImageUploadCompletion)completion; { self = [super init]; if (self) { + self.flickrKit = flickrKit; self.image = nil; self.assetURL = assetURL; self.args = args; @@ -93,7 +96,7 @@ - (NSMutableURLRequest *) createRequest:(NSError **)error { //#endif // Build a URL to the upload service - FKURLBuilder *urlBuilder = [[FKURLBuilder alloc] init]; + FKURLBuilder *urlBuilder = [[FKURLBuilder alloc] initWithFlickrKit:self.flickrKit]; NSDictionary *args = [urlBuilder signedArgsFromParameters:newArgs method:FKHttpMethodPOST url:[NSURL URLWithString:@"https://api.flickr.com/services/upload/"]]; // Form multipart needs a boundary diff --git a/Classes/Network/FKURLBuilder.h b/Classes/Network/FKURLBuilder.h index 5d06b9b..3ec3176 100644 --- a/Classes/Network/FKURLBuilder.h +++ b/Classes/Network/FKURLBuilder.h @@ -11,8 +11,12 @@ typedef enum { FKHttpMethodPOST } FKHttpMethod; +@class FlickrKit; + @interface FKURLBuilder : NSObject +- (id)initWithFlickrKit:(FlickrKit *)flickrKit; + #pragma mark - URL Encryption - (NSURL *) oauthURLFromBaseURL:(NSURL *)inURL method:(FKHttpMethod)method params:(NSDictionary *)params; diff --git a/Classes/Network/FKURLBuilder.m b/Classes/Network/FKURLBuilder.m index 01c0d7b..cd34fa0 100644 --- a/Classes/Network/FKURLBuilder.m +++ b/Classes/Network/FKURLBuilder.m @@ -11,8 +11,28 @@ #import "FlickrKit.h" #import "FKUtilities.h" +@interface FKURLBuilder () +@property (nonatomic, strong) FlickrKit *flickrKit; +@end + @implementation FKURLBuilder +- (id)initWithFlickrKit:(FlickrKit *)flickrKit { + self = [super init]; + if (self) { + self.flickrKit = flickrKit; + } + return self; +} + +- (id)init { + self = [super init]; + if (self) { + NSAssert(false, @"FKURLBuilder must be initialised with a FlickrKit instance"); + } + return self; +} + #pragma mark - URL Encryption - (NSURL *) oauthURLFromBaseURL:(NSURL *)inURL method:(FKHttpMethod)method params:(NSDictionary *)params { @@ -50,17 +70,17 @@ - (NSDictionary *) signedOAuthHTTPQueryParameters:(NSDictionary *)params baseURL newArgs[@"oauth_timestamp"] = [NSString stringWithFormat:@"%f", time]; newArgs[@"oauth_version"] = @"1.0"; newArgs[@"oauth_signature_method"] = @"HMAC-SHA1"; - newArgs[@"oauth_consumer_key"] = [FlickrKit sharedFlickrKit].apiKey; + newArgs[@"oauth_consumer_key"] = self.flickrKit.apiKey; - if (!params[@"oauth_token"] && [FlickrKit sharedFlickrKit].authToken) { - newArgs[@"oauth_token"] = [FlickrKit sharedFlickrKit].authToken; + if (!params[@"oauth_token"] && self.flickrKit.authToken) { + newArgs[@"oauth_token"] = self.flickrKit.authToken; } NSString *signatureKey = nil; - if ([FlickrKit sharedFlickrKit].authSecret) { - signatureKey = [NSString stringWithFormat:@"%@&%@", [FlickrKit sharedFlickrKit].secret, [FlickrKit sharedFlickrKit].authSecret]; + if (self.flickrKit.authSecret) { + signatureKey = [NSString stringWithFormat:@"%@&%@", self.flickrKit.secret, self.flickrKit.authSecret]; } else { - signatureKey = [NSString stringWithFormat:@"%@&", [FlickrKit sharedFlickrKit].secret]; + signatureKey = [NSString stringWithFormat:@"%@&", self.flickrKit.secret]; } NSMutableString *baseString = [NSMutableString string]; @@ -100,12 +120,12 @@ - (NSString *) signedQueryStringFromParameters:(NSDictionary *)params { //private - (NSArray *) signedArgumentComponentsFromParameters:(NSDictionary *)params { NSMutableDictionary *args = params ? [params mutableCopy] : [NSMutableDictionary dictionary]; - if ([FlickrKit sharedFlickrKit].apiKey) { - args[@"api_key"] = [FlickrKit sharedFlickrKit].apiKey; + if (self.flickrKit.apiKey) { + args[@"api_key"] = self.flickrKit.apiKey; } NSMutableArray *argArray = [NSMutableArray array]; - NSMutableString *sigString = [NSMutableString stringWithString:[FlickrKit sharedFlickrKit].secret ? [FlickrKit sharedFlickrKit].secret : @""]; + NSMutableString *sigString = [NSMutableString stringWithString:self.flickrKit.secret ? self.flickrKit.secret : @""]; NSArray *sortedKeys = [[args allKeys] sortedArrayUsingSelector:@selector(compare:)]; for (NSString *key in sortedKeys) { @@ -123,7 +143,7 @@ - (NSArray *) signedArgumentComponentsFromParameters:(NSDictionary *)params { #pragma mark - Args as array - (NSDictionary *) signedArgsFromParameters:(NSDictionary *)params method:(FKHttpMethod)method url:(NSURL *)url { - if ([FlickrKit sharedFlickrKit].isAuthorized) { + if (self.flickrKit.isAuthorized) { return [self signedOAuthHTTPQueryParameters:params baseURL:url method:method]; } else { NSMutableDictionary *returnDict = [NSMutableDictionary dictionary]; diff --git a/Classes/Network/Reachability/FKReachability.h b/Classes/Network/Reachability/FKReachability.h deleted file mode 100755 index 27155c2..0000000 --- a/Classes/Network/Reachability/FKReachability.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - - File: Reachability.h - Abstract: Basic demonstration of how to use the SystemConfiguration Reachablity APIs. - - Version: 2.2 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. - ("Apple") in consideration of your agreement to the following terms, and your - use, installation, modification or redistribution of this Apple software - constitutes acceptance of these terms. If you do not agree with these terms, - please do not use, install, modify or redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and subject - to these terms, Apple grants you a personal, non-exclusive license, under - Apple's copyrights in this original Apple software (the "Apple Software"), to - use, reproduce, modify and redistribute the Apple Software, with or without - modifications, in source and/or binary forms; provided that if you redistribute - the Apple Software in its entirety and without modifications, you must retain - this notice and the following text and disclaimers in all such redistributions - of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may be used - to endorse or promote products derived from the Apple Software without specific - prior written permission from Apple. Except as expressly stated in this notice, - no other rights or licenses, express or implied, are granted by Apple herein, - including but not limited to any patent rights that may be infringed by your - derivative works or by other works in which the Apple Software may be - incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO - WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED - WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN - COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR - DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF - CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF - APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2010 Apple Inc. All Rights Reserved. - - */ - - -#import -#import -#import - -typedef enum { - NotReachable = 0, - ReachableViaWiFi, - ReachableViaWWAN -} NetworkStatus; -#define kReachabilityChangedNotification @"kNetworkReachabilityChangedNotification" - -@interface FKReachability: NSObject -{ - BOOL localWiFiRef; - SCNetworkReachabilityRef reachabilityRef; -} - -//reachabilityWithHostName- Use to check the reachability of a particular host name. -+ (FKReachability*) reachabilityWithHostName: (NSString*) hostName; - -//reachabilityWithAddress- Use to check the reachability of a particular IP address. -+ (FKReachability*) reachabilityWithAddress: (const struct sockaddr_in*) hostAddress; - -//reachabilityForInternetConnection- checks whether the default route is available. -// Should be used by applications that do not connect to a particular host -+ (FKReachability*) reachabilityForInternetConnection; - -//reachabilityForLocalWiFi- checks whether a local wifi connection is available. -+ (FKReachability*) reachabilityForLocalWiFi; - -//Start listening for reachability notifications on the current run loop -- (BOOL) startNotifier; -- (void) stopNotifier; - -- (NetworkStatus) currentReachabilityStatus; -//WWAN may be available, but not active until a connection has been established. -//WiFi may require a connection for VPN on Demand. -- (BOOL) connectionRequired; -@end - - diff --git a/Classes/Network/Reachability/FKReachability.m b/Classes/Network/Reachability/FKReachability.m deleted file mode 100755 index e7a5d57..0000000 --- a/Classes/Network/Reachability/FKReachability.m +++ /dev/null @@ -1,272 +0,0 @@ -/* - - File: Reachability.m - Abstract: Basic demonstration of how to use the SystemConfiguration Reachablity APIs. - - Version: 2.2 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. - ("Apple") in consideration of your agreement to the following terms, and your - use, installation, modification or redistribution of this Apple software - constitutes acceptance of these terms. If you do not agree with these terms, - please do not use, install, modify or redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and subject - to these terms, Apple grants you a personal, non-exclusive license, under - Apple's copyrights in this original Apple software (the "Apple Software"), to - use, reproduce, modify and redistribute the Apple Software, with or without - modifications, in source and/or binary forms; provided that if you redistribute - the Apple Software in its entirety and without modifications, you must retain - this notice and the following text and disclaimers in all such redistributions - of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may be used - to endorse or promote products derived from the Apple Software without specific - prior written permission from Apple. Except as expressly stated in this notice, - no other rights or licenses, express or implied, are granted by Apple herein, - including but not limited to any patent rights that may be infringed by your - derivative works or by other works in which the Apple Software may be - incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO - WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED - WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN - COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR - DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF - CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF - APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2010 Apple Inc. All Rights Reserved. - - */ - -#import -#import -#import -#import -#import -#import - -#import - -#import "FKReachability.h" - -#define kShouldPrintReachabilityFlags 0 - -static void PrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* comment) -{ -#if kShouldPrintReachabilityFlags - - DULog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n", - (flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-', - (flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-', - - (flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-', - (flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-', - (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-', - (flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-', - (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-', - (flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-', - (flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-', - comment - ); -#endif -} - - -@implementation FKReachability -static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info) -{ -#pragma unused (target, flags) - NSCAssert(info != NULL, @"info was NULL in ReachabilityCallback"); - //NSCAssert([(NSObject*) info isKindOfClass: [Reachability class]], @"info was wrong class in ReachabilityCallback"); - - //We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively - // in case someon uses the Reachablity object in a different thread. - @autoreleasepool { - - FKReachability* noteObject = (__bridge FKReachability*) info; - // Post a notification to notify the client that the network reachability changed. - [[NSNotificationCenter defaultCenter] postNotificationName: kReachabilityChangedNotification object: noteObject]; - - } -} - -- (BOOL) startNotifier -{ - BOOL retVal = NO; - SCNetworkReachabilityContext context = {0, (__bridge void *)(self), NULL, NULL, NULL}; - if(SCNetworkReachabilitySetCallback(reachabilityRef, ReachabilityCallback, &context)) - { - if(SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)) - { - retVal = YES; - } - } - return retVal; -} - -- (void) stopNotifier -{ - if(reachabilityRef!= NULL) - { - SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); - } -} - -- (void) dealloc -{ - [self stopNotifier]; - if(reachabilityRef!= NULL) - { - CFRelease(reachabilityRef); - } -} - -+ (FKReachability*) reachabilityWithHostName: (NSString*) hostName; -{ - FKReachability* retVal = NULL; - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]); - if(reachability!= NULL) - { - retVal= [[self alloc] init]; - if(retVal!= NULL) - { - retVal->reachabilityRef = reachability; - retVal->localWiFiRef = NO; - } - } - return retVal; -} - -+ (FKReachability*) reachabilityWithAddress: (const struct sockaddr_in*) hostAddress; -{ - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)hostAddress); - FKReachability* retVal = NULL; - if(reachability!= NULL) - { - retVal= [[self alloc] init]; - if(retVal!= NULL) - { - retVal->reachabilityRef = reachability; - retVal->localWiFiRef = NO; - } - } - return retVal; -} - -+ (FKReachability*) reachabilityForInternetConnection; -{ - struct sockaddr_in zeroAddress; - bzero(&zeroAddress, sizeof(zeroAddress)); - zeroAddress.sin_len = sizeof(zeroAddress); - zeroAddress.sin_family = AF_INET; - return [self reachabilityWithAddress: &zeroAddress]; -} - -+ (FKReachability*) reachabilityForLocalWiFi; -{ - struct sockaddr_in localWifiAddress; - bzero(&localWifiAddress, sizeof(localWifiAddress)); - localWifiAddress.sin_len = sizeof(localWifiAddress); - localWifiAddress.sin_family = AF_INET; - // IN_LINKLOCALNETNUM is defined in as 169.254.0.0 - localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM); - FKReachability* retVal = [self reachabilityWithAddress: &localWifiAddress]; - if(retVal!= NULL) - { - retVal->localWiFiRef = YES; - } - return retVal; -} - -#pragma mark Network Flag Handling - -- (NetworkStatus) localWiFiStatusForFlags: (SCNetworkReachabilityFlags) flags -{ - PrintReachabilityFlags(flags, "localWiFiStatusForFlags"); - - BOOL retVal = NotReachable; - if((flags & kSCNetworkReachabilityFlagsReachable) && (flags & kSCNetworkReachabilityFlagsIsDirect)) - { - retVal = ReachableViaWiFi; - } - return retVal; -} - -- (NetworkStatus) networkStatusForFlags: (SCNetworkReachabilityFlags) flags -{ - PrintReachabilityFlags(flags, "networkStatusForFlags"); - if ((flags & kSCNetworkReachabilityFlagsReachable) == 0) - { - // if target host is not reachable - return NotReachable; - } - - BOOL retVal = NotReachable; - - if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0) - { - // if target host is reachable and no connection is required - // then we'll assume (for now) that your on Wi-Fi - retVal = ReachableViaWiFi; - } - - - if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || - (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)) - { - // ... and the connection is on-demand (or on-traffic) if the - // calling application is using the CFSocketStream or higher APIs - - if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0) - { - // ... and no [user] intervention is needed - retVal = ReachableViaWiFi; - } - } - - if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) - { - // ... but WWAN connections are OK if the calling application - // is using the CFNetwork (CFSocketStream?) APIs. - retVal = ReachableViaWWAN; - } - return retVal; -} - -- (BOOL) connectionRequired; -{ - NSAssert(reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef"); - SCNetworkReachabilityFlags flags; - if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) - { - return (flags & kSCNetworkReachabilityFlagsConnectionRequired); - } - return NO; -} - -- (NetworkStatus) currentReachabilityStatus -{ - NSAssert(reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef"); - NetworkStatus retVal = NotReachable; - SCNetworkReachabilityFlags flags; - if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) - { - if(localWiFiRef) - { - retVal = [self localWiFiStatusForFlags: flags]; - } - else - { - retVal = [self networkStatusForFlags: flags]; - } - } - return retVal; -} -@end