- Add Facebook SDK

- Add PNUser Login
This commit is contained in:
giuseppenuc committed 2016-02-12 00:01:51 +01:00
1 parent f2885301b9
commit a6dcf672bb
370 files changed
+44655 -2705

No files matched your search

+50 -1
View File
@@ -16,6 +16,23 @@
* @return singleton
*/
+ (instancetype _Nonnull) currentUser;
/**
* reset current user and gets new singleton object of current user session.
*
* @return <#return value description#>
*/
+ (instancetype _Nonnull) resetUser;
/**
* <#Description#>
*
* @param password <#password description#>
*
* @return <#return value description#>
*/
+ (BOOL) isValidPassword:(NSString* _Nonnull) password;
/**
* <#Description#>
*
@@ -35,7 +52,21 @@
*
* @return <#return value description#>
*/
- (BOOL) hasValidUserAndPasswordData;
- (BOOL) hasValidEmailAndPasswordData;
/**
* <#Description#>
*
* @param email <#email description#>
* @param password <#password description#>
* @param success <#success description#>
* @param failure <#failure description#>
*/
- (void) loginCurrentUserWithEmail:(NSString * _Nonnull) email
password:(NSString * _Nonnull) password
withBlockSuccess:(nullable void (^)(PNUser * _Nullable responseObject))success
failure:(nullable void (^)(NSError * _Nonnull error))failure;
/**
* <#Description#>
@@ -46,6 +77,20 @@
- (void) registerCurrentUserWithBlockSuccess:(nullable void (^)(PNUser * _Nullable responseObject))success
failure:(nullable void (^)(NSError * _Nonnull error))failure;
/**
* <#Description#>
*
* @param viewController <#viewController description#>
* @param success <#success description#>
* @param failure <#failure description#>
*/
- (void) socialLoginWithBlockSuccessFromViewController:(UIViewController* _Nonnull) viewController
blockSuccess:(nullable void (^)(PNUser * _Nullable responseObject))success
failure:(nullable void (^)(NSError * _Nonnull error))failure;
- (void) reloadFormServer;
/**
* <#Description#>
*
@@ -127,6 +172,10 @@
* <#Description#>
*/
@property (nonatomic, strong, nullable) NSNumber * loginCount;
/**
* <#Description#>
*/
@property (nonatomic) BOOL isFacebookUser;
/**
* <#Description#>
*/
+183 -16
View File
@@ -12,6 +12,10 @@
#import "PNObject+Protected.h"
#import "PNObject+PNObjectConnection.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import <FBSDKShareKit/FBSDKShareKit.h>
@interface PNUser() <PNObjectSubclassing>
@@ -38,6 +42,12 @@ static bool isFirstAccess = YES;
return SINGLETON;
}
+ (instancetype)resetUser {
[SINGLETON autoRemoveLocally];
SINGLETON = nil;
return [self currentUser];
}
#pragma mark - Life Cycle
- (instancetype)copy
@@ -62,15 +72,15 @@ static bool isFirstAccess = YES;
NSDictionary *savedUser = [[PNObjectModel sharedInstance] fetchObjectsWithClass:[self class]];
if (savedUser) {
self = [super initWithJSON:savedUser];
SINGLETON = [super initWithJSON:savedUser];
}
else {
self = [super init];
SINGLETON = [super init];
}
if (self) {
if (SINGLETON) {
}
return self;
return SINGLETON;
}
- (void) setEmail:(NSString *)email {
@@ -112,39 +122,194 @@ static bool isFirstAccess = YES;
return NO;
}
+ (BOOL) isValidPassword:(NSString* _Nonnull) password {
if ([password length] >= [[PNObjectConfig sharedInstance] minPasswordLenght]) {
return YES;
}
return NO;
}
- (void)logout {
[self autoRemoveLocally];
[self resetObject];
}
- (BOOL) hasValidUserAndPasswordData {
if(self.username && self.password && [self isValidPassword:[self password]]){
- (BOOL) hasValidEmailAndPasswordData {
if(self.email && [self.email isValidEmail] && self.password && [self isValidPassword:[self password]]){
return YES;
}
return NO;
}
- (void) registerCurrentUserWithBlockSuccess:(nullable void (^)(PNUser * _Nullable responseObject))success
failure:(nullable void (^)(NSError * _Nonnull error))failure {
- (void) autoLogin {
[self autoLoginWithBlockSuccess:nil failure:nil];
}
[self POSTWithEndpointAction:@"registration/register" Progress:nil success:^(NSURLSessionDataTask * _Nullable task, PNObject * _Nullable responseObject) {
NSLog(@"response %@",responseObject);
if(success){
success((PNUser*)responseObject);
[self saveLocally];
- (void) autoLoginWithBlockSuccess:(nullable void (^)(BOOL loginSuccess))success
failure:(nullable void (^)(NSError * _Nonnull error))failure {
[[PNObjectConfig sharedInstance] refreshTokenForUserWithBlockSuccess:^(BOOL refreshSuccess) {
if (success) {
success(refreshSuccess);
}
} failure:^(NSError * _Nonnull error) {
if (failure) {
failure(error);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLogDebug(@"error : %ld",[error code]);
}];
}
- (void) reloadFormServer {
///api/v1/user/profile
[self autoLoginWithBlockSuccess:^(BOOL loginSuccess) {
[self GETWithEndpointAction:@"user/profile"
progress:nil
success:^(NSURLSessionDataTask * _Nullable task, id _Nullable responseObject) {
NSLogDebug(@"%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLogDebug(@"%@",error);
}];
} failure:^(NSError * _Nonnull error) {
NSLogDebug(@"error : %@",error);
}];
}
- (void) registerWithBlockSuccess:(nullable void (^)(PNUser * _Nullable responseObject))success
failure:(nullable void (^)(NSError * _Nonnull error))failure {
[self POSTWithEndpointAction:@"registration/register" parameters:[self JSONFormObject]
progress:nil
success:^(NSURLSessionDataTask * _Nullable task, PNObject * _Nullable responseObject) {
NSLog(@"response %@",responseObject);
if(success){
success(self);
[self saveLocally];
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLogDebug(@"error : %ld",[error code]);
if (failure) {
failure(error);
}
}];
}
- (void) socialLoginWithBlockSuccessFromViewController:(UIViewController* _Nonnull) viewController
blockSuccess:(nullable void (^)(PNUser * _Nullable responseObject))success
failure:(nullable void (^)(NSError * _Nonnull error))failure {
if ([FBSDKAccessToken currentAccessToken]) {
//FBSDKProfile *user = [FBSDKProfile currentProfile];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields": @"first_name, last_name, link, birthday, email, gender"}];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
NSLogDebug(@"%@",result);
NSLogDebug(@"%@",error);
if (error) {
if (failure) {
failure(error);
}
}
else {
[self setFacebookAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];
[self setFirstName:[result objectForKey:@"first_name"]];
[self setLastName:[result objectForKey:@"last_name"]];
[self setEmail:[result objectForKey:@"email"]];
[self setFacebookId:[result objectForKey:@"id"]];
NSString *gender = [[result objectForKey:@"gender"] isEqualToString:@"male"] ? @"M" : @"F";
[self setSex:gender];
NSArray *birthArray = [[result objectForKey:@"birthday" ] componentsSeparatedByString: @"/"];
//NSMutableString *birthString = [NSMutableString stringWithString:[[[[[birthArray objectAtIndex:1] stringByAppendingString:@"/"] stringByAppendingString:[birthArray objectAtIndex:0]] stringByAppendingString:@"/"] stringByAppendingString:[birthArray objectAtIndex:2]]];
}
/*[UserDataManager setParameter:DEF_PROFILE_FIRSTNAME withValue:user.firstName];
[UserDataManager setParameter:DEF_PROFILE_LASTNAME withValue:user.lastName];
NSArray *birthArray = [[result objectForKey:@"birthday" ] componentsSeparatedByString: @"/"];
NSMutableString *birthString = [NSMutableString stringWithString:[[[[[birthArray objectAtIndex:1] stringByAppendingString:@"/"] stringByAppendingString:[birthArray objectAtIndex:0]] stringByAppendingString:@"/"] stringByAppendingString:[birthArray objectAtIndex:2]]];
NSString *gender = [[result objectForKey:@"gender"] isEqualToString:@"male"] ? @"M" : @"F";
[UserDataManager setParameter:DEF_PROFILE_BIRTH withValue:birthString];
[UserDataManager setParameter:DEF_PROFILE_GENDER withValue:gender];
[UserDataManager setParameter:DEF_PROFILE_EMAIL withValue:[result objectForKey:@"email"]];
[UserDataManager setParameter:DEF_PROFILE_AVATAR withValue:[NSNumber numberWithInt:1]];
[UserDataManager setParameter:DEF_PROFILE_FB_ID withValue:[result objectForKey:@"id"]];*/
//[self setFacebookId:[user userID]];
}];
}
else {
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions: @[@"public_profile",@"email"] fromViewController:viewController handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
NSLog(@"Process error");
} else if (result.isCancelled) {
NSLog(@"Cancelled");
} else {
NSLog(@"Logged in");
}
}];
}
}
- (void) socialLoginWithBlockSuccess:(void (^)(PNUser * _Nullable))success
failure:(void (^)(NSError * _Nonnull))failure {
/*[self POSTWithEndpointAction:@"registration/register" progress:nil success:^(NSURLSessionDataTask * _Nullable task, PNObject * _Nullable responseObject) {
NSLog(@"response %@",responseObject);
if(success){
success(self);
[self saveLocally];
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLogDebug(@"error : %ld",[error code]);
if (failure) {
failure(error);
}
}];*/
}
- (void) loginCurrentUserWithEmail:(NSString * _Nonnull) email
password:(NSString * _Nonnull) password
withBlockSuccess:(nullable void (^)(PNUser * _Nullable responseObject))success
failure:(nullable void (^)(NSError * _Nonnull error))failure {
[[PNObjectConfig sharedInstance] refreshTokenForUserWithEmail:email password:password withBlockSuccess:^(BOOL refreshSuccess) {
if (refreshSuccess) {
if (success) {
success([PNUser currentUser]);
}
}
} failure:failure];
}
#pragma mark PNObjectSubclassing Protocol
+ (NSDictionary *)objcetMapping {
NSDictionary *mapping = @{
@"userId":@"id",
@"userUUID":@"uuid",
@"firstName":@"firstName",
@"lastName":@"lastName",
@"profileImage":@"profileImage",
@@ -159,10 +324,12 @@ static bool isFirstAccess = YES;
@"emailVerifiedDate":@"emailVerifiedDate",
@"email":@"email",
@"username":@"username",
@"publicProfile":@"public_profile",
@"publicProfile":@"publicProfile",
@"loginCount":@"login_count",
@"facebookId":@"facebookId",
@"facebookAccessToken":@"facebookAccessToken",
@"isFacebookUser":@"isFacebookUser",
@"registeredAt":@"registeredAt",
};
return mapping;
}
+6 -12
View File
@@ -10,22 +10,16 @@
@interface PNObject (PNObjectConnection)
+ (void) GETWithProgress:(nullable void (^)(NSProgress * _Nonnull downloadProgress)) downloadProgress
success:(nullable void (^)(NSURLSessionDataTask * _Nullable task, PNObject * _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error))failure;
+ (void) GETWithEndpointAction:(NSString * _Nonnull) endPoint
Progress:(nullable void (^)(NSProgress * _Nonnull downloadProgress)) downloadProgress
success:(nullable void (^)(NSURLSessionDataTask * _Nullable task, PNObject * _Nullable responseObject))success
- (void) GETWithEndpointAction:(NSString * _Nonnull) endPoint
progress:(nullable void (^)(NSProgress * _Nonnull downloadProgress)) downloadProgress
success:(nullable void (^)(NSURLSessionDataTask * _Nullable task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error))failure;
+ (void) POSTWithProgress:(nullable void (^)(NSProgress * _Nonnull uploadProgress)) uploadProgress
success:(nullable void (^)(NSURLSessionDataTask * _Nullable task, PNObject * _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error))failure;
- (void) POSTWithEndpointAction:(NSString * _Nonnull) endPoint
Progress:(nullable void (^)(NSProgress * _Nonnull uploadProgress)) uploadProgress
success:(nullable void (^)(NSURLSessionDataTask * _Nullable task, PNObject * _Nullable responseObject))success
parameters:(NSDictionary * _Nonnull) parameters
progress:(nullable void (^)(NSProgress * _Nonnull uploadProgress)) uploadProgress
success:(nullable void (^)(NSURLSessionDataTask * _Nullable task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error))failure;
@end
+45 -94
View File
@@ -16,54 +16,18 @@
@implementation PNObject (PNObjectConnection)
+ (void) GETWithProgress:(nullable void (^)(NSProgress * _Nonnull downloadProgress)) downloadProgress
success:(nullable void (^)(NSURLSessionDataTask * _Nullable task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error))failure {
if ([[PNObjectConfig sharedInstance] currentOauthCredential] && ![[[PNObjectConfig sharedInstance] currentOauthCredential] isExpired]) {
[[[PNObjectConfig sharedInstance] manager] GET:[[[PNObjectConfig sharedInstance] baseUrl] stringByAppendingFormat:@"%@",[[self class] objectEndPoint]]
parameters:nil
progress:downloadProgress
success:^(NSURLSessionDataTask *task, id responseObject) {
id PNObjectResponse = [[[self class] alloc] initWithJSON:[responseObject copy]];
if (success) {
success(task,PNObjectResponse);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(task,error);
}
}];
}
else {
[[PNObjectConfig sharedInstance] refreshTokenForClientCredentialWithBlockSuccess:^(BOOL refreshSuccess) {
[self GETWithProgress:downloadProgress success:success failure:failure];
} failure:^(NSError * _Nonnull error) {
}];
}
}
+ (void) GETWithEndpointAction:(NSString * _Nonnull) endPoint
Progress:(nullable void (^)(NSProgress * _Nonnull downloadProgress)) downloadProgress
success:(nullable void (^)(NSURLSessionDataTask * _Nullable task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error))failure {
- (void) GETWithEndpointAction:(NSString * _Nonnull) endPoint
progress:(nullable void (^)(NSProgress * _Nonnull downloadProgress)) downloadProgress
success:(nullable void (^)(NSURLSessionDataTask * _Nullable task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error))failure {
if ([[PNObjectConfig sharedInstance] currentOauthCredential] && ![[[PNObjectConfig sharedInstance] currentOauthCredential] isExpired]) {
[[[PNObjectConfig sharedInstance] manager] GET:[[[PNObjectConfig sharedInstance] baseUrl] stringByAppendingFormat:@"%@",endPoint] parameters:nil progress:downloadProgress success:^(NSURLSessionDataTask *task, id responseObject) {
id PNObjectResponse = [[[self class] alloc] initWithJSON:[responseObject copy]];
if (success) {
success(task,PNObjectResponse);
success(task,[[self class] parseObjectFromResponse:responseObject]);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
@@ -75,30 +39,27 @@
else {
[[PNObjectConfig sharedInstance] refreshTokenForClientCredentialWithBlockSuccess:^(BOOL refreshSuccess) {
[self GETWithProgress:downloadProgress success:success failure:failure];
[self GETWithEndpointAction:endPoint progress:downloadProgress success:success failure:failure];
} failure:^(NSError * _Nonnull error) {
if (failure) {
failure(nil,error);
}
}];
}
}
- (void) POSTWithEndpointAction:(NSString * _Nonnull) endPoint
Progress:(nullable void (^)(NSProgress * _Nonnull uploadProgress)) uploadProgress
success:(nullable void (^)(NSURLSessionDataTask * _Nullable task, PNObject * _Nullable responseObject))success
parameters:(NSDictionary * _Nonnull) parameters
progress:(nullable void (^)(NSProgress * _Nonnull uploadProgress)) uploadProgress
success:(nullable void (^)(NSURLSessionDataTask * _Nullable task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error))failure {
if ([[PNObjectConfig sharedInstance] currentOauthCredential] && ![[[PNObjectConfig sharedInstance] currentOauthCredential] isExpired]) {
[[[PNObjectConfig sharedInstance] manager] POST:[[[PNObjectConfig sharedInstance] baseUrl] stringByAppendingFormat:@"%@",endPoint] parameters:[self JSONFormObject] progress:uploadProgress success:^(NSURLSessionDataTask *task, id responseObject) {
id PNObjectResponse;
if (responseObject) {
PNObjectResponse = [[[self class] alloc] initWithJSON:[responseObject copy]];
}
[[[PNObjectConfig sharedInstance] manager] POST:[[[PNObjectConfig sharedInstance] baseUrl] stringByAppendingFormat:@"%@",endPoint] parameters:parameters progress:uploadProgress success:^(NSURLSessionDataTask *task, id responseObject) {
if (success) {
success(task,PNObjectResponse);
success(task,[[self class] parseObjectFromResponse:responseObject]);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
@@ -111,9 +72,9 @@
else {
[[PNObjectConfig sharedInstance] refreshTokenForClientCredentialWithBlockSuccess:^(BOOL refreshSuccess) {
[self POSTWithEndpointAction:endPoint Progress:uploadProgress success:success failure:failure];
[self POSTWithEndpointAction:endPoint parameters:parameters progress:uploadProgress success:success failure:failure];
} failure:^(NSError * _Nonnull error) {
if (failure) {
failure(nil,error);
}
@@ -122,53 +83,43 @@
}
#pragma mark Private Methods
+ (id _Nonnull) parseObjectFromResponse:(id _Nullable) response {
id PNObjectResponse;
if (response) {
if ([response isKindOfClass:[NSDictionary class]] && [[response allKeys] count] > 0) {
PNObjectResponse = [[[self class] alloc] initWithJSON:[response copy]];
}
else if ([response isKindOfClass:[NSArray class]] && [response count] > 0){
NSMutableArray * resposeArray = [[NSMutableArray alloc] init];
for (id singleObjectDict in response) {
if ([singleObjectDict isKindOfClass:[NSDictionary class]]) {
id singleObject = [[[self class] alloc] initWithJSON:singleObjectDict];
[resposeArray addObject:singleObject];
}
}
PNObjectResponse = resposeArray;
}
}
return PNObjectResponse;
}
+ (NSError* _Nonnull) getErrorFromTask:(NSURLSessionDataTask* _Nonnull) task andError:(NSError * _Nonnull) error {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData: errorData options:kNilOptions error:nil];
return [NSError errorWithDomain:[error domain] code:response.statusCode userInfo:serializedData];
}
/*+ (nullable NSURLSessionDataTask *) POSTConstructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> _Nonnull formData))block
progress:(nullable void (^)(NSProgress * _Nonnull uploadProgress)) uploadProgress
success:(nullable void (^)(NSURLSessionDataTask * _Nullable task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure {
NSDictionary *parameters = [NSDictionary dictionary];
[[[PNObjectConfig sharedInstance] manager] POST:[[[PNObjectConfig sharedInstance] baseUrl] stringByAppendingFormat:@"%@",[[self class] objectEndPoint]]
parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
}
- (NSURLSessionDataTask * _Nonnull) GETWithProgress:(nullable void (^)(NSProgress * _Nonnull downloadProgress)) downloadProgress
success:(nullable void (^)(NSURLSessionDataTask * _Nullable task, PNObject * _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error))failure {
return [[[PNObjectConfig sharedInstance] manager] GET:[[[PNObjectConfig sharedInstance] baseUrl] stringByAppendingFormat:@"%@",[[self class] objectEndPoint]] parameters:nil progress:downloadProgress success:^(NSURLSessionDataTask *task, id responseObject) {
[self resetObject];
[self populateObjectFromJSON:responseObject];
if (success) {
success(task,self);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(task,error);
}
}];
}*/
#pragma mark -
@end
+8 -4
View File
@@ -93,7 +93,11 @@
},
@"NSNumber" : ^{
NSInteger val = [value integerValue];
NSInteger val = 0;
if (value && ![value isKindOfClass:[NSNull class]]) {
val = [value integerValue];
}
[self setValue:@(val) forKey:propertyName];
},
@"NSDate" : ^{
@@ -196,7 +200,7 @@
[self setValue:@(NO) forKey:propertyName];
},
@"NSString" : ^{
[self setValue:[[NSString alloc] init] forKey:propertyName];
[self setValue:[NSString string] forKey:propertyName];
},
@"NSNumber" : ^{
[self setValue:[[NSNumber alloc] init] forKey:propertyName];
@@ -205,10 +209,10 @@
[self setValue:[[NSDate alloc] init] forKey:propertyName];
},
@"NSArray" : ^{
[self setValue:[[NSArray alloc] init] forKey:propertyName];
[self setValue:[NSArray array] forKey:propertyName];
},
@"NSMutableArray" : ^{
[self setValue:[[NSMutableArray alloc] init] forKey:propertyName];
[self setValue:[NSMutableArray array] forKey:propertyName];
}
}[propertyType] ?: ^{
BOOL isPNObjectSubclass = [NSClassFromString(propertyType) isSubclassOfClass:[PNObject class]];
+71 -58
View File
@@ -76,33 +76,33 @@
- (_Nullable instancetype) init {
self = [super init];
if (self) {
if ([[self class] isSubclassOfClass:[PNObject class]]) {
NSAssert([[self class] conformsToProtocol:@protocol(PNObjectSubclassing)], @"Subclass object must conform to PNObjectSubclassing");
_objID = [[NSProcessInfo processInfo] globallyUniqueString];
_objectModel = [PNObjectModel sharedInstance];
[_objectModel setPersistencyDelegate:self];
NSMutableDictionary * objectDict = [[NSMutableDictionary alloc] initWithDictionary:[[self class] objcetMapping]];
[objectDict addEntriesFromDictionary:[PNObject objcetMapping]];
_JSONObject = objectDict;
NSAssert(_JSONObject, @"You must create objectMapping");
_singleInstance = [[self class] singleInstance];
_createdAt = [[NSDate date] toLocalTime];
}
_JSON = [[NSMutableDictionary alloc] init];
NSDictionary *properties = [PNObject propertiesForClass:self.class];
for (NSString *propertyName in properties) {
if ([propertyName isEqualToString:@"description"] || [propertyName isEqualToString:@"debugDescription"]) {
continue;
@@ -118,37 +118,37 @@
if (self) {
if ([[self class] isSubclassOfClass:[PNObject class]]) {
NSAssert([[self class] conformsToProtocol:@protocol(PNObjectSubclassing)], @"Subclass object must conform to PNObjectSubclassing Protocol");
_objID = [[NSProcessInfo processInfo] globallyUniqueString];
_objectModel = [PNObjectModel sharedInstance];
[_objectModel setPersistencyDelegate:self];
NSMutableDictionary * objectDict = [[NSMutableDictionary alloc] initWithDictionary:[[self class] objcetMapping]];
[objectDict addEntriesFromDictionary:[PNObject objcetMapping]];
_JSONObject = objectDict;
NSAssert(_JSONObject, @"You must create objectMapping");
_singleInstance = [[self class] singleInstance];
_createdAt = [[NSDate date] toLocalTime];
}
NSDictionary *properties = [PNObject propertiesForClass:self.class];
for (NSString *propertyName in properties) {
if ([propertyName isEqualToString:@"description"] || [propertyName isEqualToString:@"debugDescription"]) {
continue;
}
[self addObserver:self forKeyPath:propertyName options:NSKeyValueObservingOptionNew context:nil];
}
NSAssert(_JSONObject, @"You must create objectMapping");
_JSON = [[NSMutableDictionary alloc] initWithDictionary:JSON];
[self populateObjectFromJSON:_JSON];
}
return self;
@@ -157,28 +157,28 @@
- (NSDictionary * _Nonnull)reverseMapping
{
NSMutableDictionary *JSON = [NSMutableDictionary dictionary];
NSString *mappedJSONKey;
NSString *mappedJSONType;
NSDictionary *properties = [PNObject propertiesForClass:self.class];
for (NSString* propertyName in _JSONObject) {
id mappingValue = [_JSONObject objectForKey:propertyName];
if([mappingValue isKindOfClass:NSDictionary.class]) {
mappedJSONKey = [mappingValue valueForKey:@"key"];
mappedJSONType = [mappingValue valueForKey:@"type"];
} else {
mappedJSONKey = mappingValue;
}
NSString *propertyType = [properties valueForKey:propertyName];
id value = [self valueForKey:propertyName];
NSLog(@"PropertyName PropertyType Value: %@ - %@ - %@",propertyName,propertyType,value);
((void (^)())@{
@"c" : ^{
char val = [value charValue];
@@ -208,14 +208,14 @@
BOOL val = [value boolValue];
[JSON setValue:@(val) forKey:propertyName];
},
@"UIImage" : ^{
UIImage *image = [UIImage imageWithData:value];
[JSON setValue:image forKey:propertyName];
},
@"NSURL" : ^{
NSURL *url = value;
if (![self isObjNull:url]) {
[JSON setValue:[url absoluteString] forKey:propertyName];
}
@@ -246,10 +246,10 @@
[invocation invoke];
NSDictionary *returnValue;
[invocation getReturnValue:&returnValue];
[arr addObject:returnValue];
}
[JSON setValue:arr forKey:propertyName];
},
@"NSMutableArray" : ^{
@@ -257,7 +257,7 @@
for(id JSONObject in value) {
PNObject *val = [[NSClassFromString(mappedJSONType) alloc] initWithJSON:JSONObject];
[arr addObject:val];
SEL selector = NSSelectorFromString(@"JSONObject");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[PNObject class] instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
@@ -266,7 +266,7 @@
NSDictionary *returnValue;
[invocation getReturnValue:&returnValue];
}
[JSON setValue:arr forKey:propertyName];
}
}[propertyType] ?: ^{
@@ -279,7 +279,7 @@
[invocation invoke];
NSDictionary *returnValue;
[invocation getReturnValue:&returnValue];
[JSON setValue:returnValue forKey:propertyName];
}
else {
@@ -287,20 +287,20 @@
}
})();
}
_JSON = JSON;
return _JSON;
}
- (NSDictionary * _Nonnull) JSONFormObject {
NSMutableDictionary *JSONFormObject = [[NSMutableDictionary alloc] init];
NSDictionary *JSONMap = [[self class] objcetMapping];
for (NSString *key in JSONMap) {
if ([_JSON objectForKey:[JSONMap objectForKey:key]]) {
[JSONFormObject setObject:[_JSON objectForKey:[JSONMap objectForKey:key]] forKey:[JSONMap objectForKey:key]];
}
@@ -332,16 +332,16 @@
#pragma mark PNObjectPersistency protocol
- (BOOL) initObjectPersistency {
BOOL isDir=YES;
NSError *error;
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSFileManager *fileManager= [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:[docDir stringByAppendingFormat:@"/%@",PNOBJECT_DIR] isDirectory:&isDir]) {
if (![[NSFileManager defaultManager] createDirectoryAtPath:[docDir stringByAppendingFormat:@"/%@",PNOBJECT_DIR] withIntermediateDirectories:NO attributes:nil error:&error]) {
#ifdef DEBUG
NSLogDebug(@"Create directory error: %@", error);
@@ -356,9 +356,9 @@
}
- (id _Nonnull) saveLocally {
__weak id weakSelf = self;
return [_objectModel saveLocally:weakSelf];
}
@@ -370,33 +370,46 @@
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
[_JSON setObject:[change objectForKey:@"new"] forKey:[[[self class] objcetMapping] objectForKey:keyPath]];
@try {
if ([change objectForKey:@"new"]) {
[_JSON setObject:[change objectForKey:@"new"] forKey:[[[self class] objcetMapping] objectForKey:keyPath]];
}
else {
[_JSON removeObjectForKey:[[[self class] objcetMapping] objectForKey:keyPath]];
}
}
@catch (NSException *exception) {
}
@finally {
}
}
- (void)dealloc
{
NSDictionary *properties = [PNObject propertiesForClass:self.class];
for (NSString *propertyName in properties) {
if ([propertyName isEqualToString:@"description"] || [propertyName isEqualToString:@"debugDescription"]) {
continue;
}
@try {
[self removeObserver:self forKeyPath:propertyName];
}
@catch (NSException *exception) {
}
@finally {
}
}
_JSON = nil;
_JSONObject = nil;
_objID = nil;
_createdAt = nil;
}
+12
View File
@@ -141,6 +141,18 @@ extern NSString* _Nonnull const Client_Secret;
- (void) refreshTokenForUserWithBlockSuccess:(nullable void (^)(BOOL refreshSuccess))success
failure:(nullable void (^)(NSError * _Nonnull error))failure;
/**
* <#Description#>
*
* @param email <#email description#>
* @param password <#password description#>
* @param success <#success description#>
* @param failure <#failure description#>
*/
- (void) refreshTokenForUserWithEmail:(NSString * _Nonnull) email
password:(NSString * _Nonnull) password
withBlockSuccess:(nullable void (^)(BOOL refreshSuccess))success
failure:(nullable void (^)(NSError * _Nonnull error))failure;
/**
* <#Description#>
*/
+94 -41
View File
@@ -10,6 +10,8 @@
#import "PNObjectConstants.h"
#import "PNUser.h"
#import "AFJSONResponseSerializerWithData.h"
#import "NSString+Helper.h"
#import "PNObject+Protected.h"
NSString * const PNObjectLocalNotificationRefreshTokenClientCredentialSuccess = @"PNObjectLocalNotificationRefreshTokenClientCredentialSuccess";
@@ -63,7 +65,7 @@ static bool isFirstAccess = YES;
isFirstAccess = NO;
SINGLETON = [[super allocWithZone:NULL] init];
});
return SINGLETON;
}
@@ -75,13 +77,13 @@ static bool isFirstAccess = YES;
+ (instancetype) initSharedInstanceForEnvironments:(NSDictionary *) endpointUrlsForEnvironments withOauth:(BOOL) oauthEnabled {
SINGLETON = [self sharedInstance];
if (SINGLETON) {
SINGLETON.oauthEnabled = oauthEnabled;
for (NSString *key in [endpointUrlsForEnvironments allKeys]) {
if ([SINGLETON.environments containsObject:key]) {
NSURL * endpointUrl = [NSURL URLWithString:[endpointUrlsForEnvironments objectForKey:key]];
if (endpointUrl) {
[SINGLETON.configuration setValue:[NSDictionary dictionaryWithObjectsAndKeys:[endpointUrl absoluteString],BaseUrl, nil] forKey:key];
@@ -90,9 +92,9 @@ static bool isFirstAccess = YES;
}
NSAssert([SINGLETON.configuration objectForKey:EnvironmentProduction], @"EnvironmentProduction must be valid endpoint url");
[SINGLETON setEnvironment:Production];
}
return SINGLETON;
}
@@ -131,31 +133,31 @@ static bool isFirstAccess = YES;
[self doesNotRecognizeSelector:_cmd];
}
self = [super init];
if (self) {
if (_oauthEnabled) {
_currentOauthCredential = [AFOAuthCredential retrieveCredentialWithIdentifier:PNObjectServiceCredentialIdentifier];
}
_environments = [[NSMutableArray alloc] initWithArray:@[EnvironmentDevelopment,EnvironmentStage,EnvironmentProduction]];
_configuration = [[NSMutableDictionary alloc] init];
_minPasswordLenght = minPassLenght;
_headerFields = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void) setEnvironment:(Environment) env {
_currentEnv = env;
_currentEndPointBaseUrl = nil;
_currentOAuthClientID = nil;
_currentOAuthClientSecret = nil;
if (env < [_environments count]) {
if ([_configuration objectForKey:[_environments objectAtIndex:env]]) {
_currentEndPointBaseUrl = [[_configuration objectForKey:[_environments objectAtIndex:env]] objectForKey:BaseUrl];
@@ -173,11 +175,11 @@ static bool isFirstAccess = YES;
}
}
NSLog(@"%@",[[_configuration objectForKey:[_environments objectAtIndex:env]] objectForKey:BaseUrl]);
NSAssert(_currentEndPointBaseUrl,@"Selected environment generate error. Please check configuration");
[self manager];
}
- (NSString *) baseUrl {
@@ -185,33 +187,33 @@ static bool isFirstAccess = YES;
}
- (AFOAuth2Manager *) manager {
BOOL canTryRefreh = NO;
if (!_manager) {
_manager = [AFOAuth2Manager manager];
}
_currentOauthCredential = [AFOAuthCredential retrieveCredentialWithIdentifier:PNObjectServiceCredentialIdentifier];
if (_oauthEnabled && _currentOAuthClientID && _currentOAuthClientSecret) {
if (![_manager clientID]) {
_manager = [AFOAuth2Manager managerWithBaseURL:[NSURL URLWithString:_currentEndPointBaseUrl] clientID:_currentOAuthClientID secret:_currentOAuthClientSecret];
}
[_manager setUseHTTPBasicAuthentication:NO];
canTryRefreh = YES;
}
for (NSString *key in [_headerFields allKeys]) {
[[_manager requestSerializer] setValue:[_headerFields objectForKey:key] forHTTPHeaderField:key];
}
if (canTryRefreh) {
if (_currentOauthCredential && ![_currentOauthCredential isExpired]) {
[[_manager requestSerializer] setAuthorizationHeaderFieldWithCredential:_currentOauthCredential];
}
@@ -227,7 +229,7 @@ static bool isFirstAccess = YES;
- (BOOL) resetToken {
if (_currentOauthCredential) {
return [AFOAuthCredential deleteCredentialWithIdentifier:PNObjectServiceCredentialIdentifier];
return [AFOAuthCredential deleteCredentialWithIdentifier:PNObjectServiceCredentialIdentifier];
}
return NO;
}
@@ -240,10 +242,10 @@ static bool isFirstAccess = YES;
- (void) refreshTokenForUserWithBlockSuccess:(nullable void (^)(BOOL refreshSuccess))success
failure:(nullable void (^)(NSError * _Nonnull error))failure {
if([PNUser currentUser] && [[PNUser currentUser] hasValidUserAndPasswordData]) {
[_manager authenticateUsingOAuthWithURLString:[_currentEndPointBaseUrl stringByAppendingString:@"oauth-token"] username:[[PNUser currentUser] username] password:[[PNUser currentUser] password] scope:nil success:^(AFOAuthCredential * _Nonnull credential) {
if([PNUser currentUser] && [[PNUser currentUser] hasValidEmailAndPasswordData]) {
[_manager authenticateUsingOAuthWithURLString:[_currentEndPointBaseUrl stringByAppendingString:@"oauth-token"] username:[[PNUser currentUser] email] password:[[PNUser currentUser] password] scope:nil success:^(AFOAuthCredential * _Nonnull credential) {
_currentOauthCredential = credential;
[AFOAuthCredential storeCredential:_currentOauthCredential withIdentifier:PNObjectServiceCredentialIdentifier];
[_manager.requestSerializer setAuthorizationHeaderFieldWithCredential:_currentOauthCredential];
@@ -258,6 +260,57 @@ static bool isFirstAccess = YES;
}
}];
}
else {
if (failure) {
NSError *error = [NSError errorWithDomain:@"" code:kHTTPStatusCodeBadRequest userInfo:nil];
failure(error);
}
}
}
- (void) refreshTokenForUserWithEmail:(NSString * _Nonnull) email
password:(NSString * _Nonnull) password
withBlockSuccess:(nullable void (^)(BOOL refreshSuccess))success
failure:(nullable void (^)(NSError * _Nonnull error))failure {
if (![email isValidEmail]) {
if (failure) {
NSError *error = [NSError errorWithDomain:NSLocalizedString(@"Email is not valid", @"") code:kHTTPStatusCodeBadRequest userInfo:nil];
failure(error);
return;
}
}
if (![PNUser isValidPassword:password]) {
if (failure) {
NSError *error = [NSError errorWithDomain:NSLocalizedString(@"Password is not valid", @"") code:kHTTPStatusCodeBadRequest userInfo:nil];
failure(error);
return;
}
}
[_manager authenticateUsingOAuthWithURLString:[_currentEndPointBaseUrl stringByAppendingString:@"oauth-token"] username:email password:password scope:nil success:^(AFOAuthCredential * _Nonnull credential) {
_currentOauthCredential = credential;
[AFOAuthCredential storeCredential:_currentOauthCredential withIdentifier:PNObjectServiceCredentialIdentifier];
[_manager.requestSerializer setAuthorizationHeaderFieldWithCredential:_currentOauthCredential];
PNUser *user = [PNUser currentUser];
[user setEmail:email];
[user setPassword:password];
[user setConfirmPassword:password];
[user saveLocally];
if (success) {
success(YES);
}
} failure:^(NSError * _Nonnull error) {
[[NSNotificationCenter defaultCenter] postNotificationName:PNObjectLocalNotificationRefreshTokenUserFail object:error];
if (failure) {
failure(error);
}
}];
}
- (void) refreshTokenForClientCredential {
@@ -267,12 +320,12 @@ static bool isFirstAccess = YES;
- (void) refreshTokenForClientCredentialWithBlockSuccess:(nullable void (^)(BOOL refreshSuccess))success
failure:(nullable void (^)(NSError * _Nonnull error))failure {
[_manager authenticateUsingOAuthWithURLString:[_currentEndPointBaseUrl stringByAppendingString:@"oauth-token"] scope:nil success:^(AFOAuthCredential * _Nonnull credential) {
_currentOauthCredential = credential;
[AFOAuthCredential storeCredential:_currentOauthCredential withIdentifier:PNObjectServiceCredentialIdentifier];
[_manager.requestSerializer setAuthorizationHeaderFieldWithCredential:_currentOauthCredential];
if (success) {
@@ -284,7 +337,7 @@ static bool isFirstAccess = YES;
failure(error);
}
}];
}
@@ -303,15 +356,15 @@ static bool isFirstAccess = YES;
}
- (void) setClientID:(NSString * _Nonnull) clientID clientSecret:(NSString* _Nonnull) clientSecret forEnv:(Environment) environment {
if ([_configuration objectForKey:[_environments objectAtIndex:environment]]) {
NSMutableDictionary *currentConfigurationDict = [[NSMutableDictionary alloc] initWithDictionary:[_configuration objectForKey:[_environments objectAtIndex:environment]]];
[currentConfigurationDict setObject:clientID forKey:Client_ID];
[currentConfigurationDict setObject:clientSecret forKey:Client_Secret];
[_configuration setObject:currentConfigurationDict forKey:[_environments objectAtIndex:environment]];
if (_currentEnv == environment) {
[self setEnvironment:environment];
}