- Add Icon

- Add LaunchImage
- Add Button tu test Token Management and refreshtoken
This commit is contained in:
giuseppenuc committed 2016-02-06 01:21:23 +01:00
1 parent 1cdb6163ef
commit 1c65349733
76 files changed
+5684 -2030

No files matched your search

+27 -1
View File
@@ -24,12 +24,34 @@
* @return <#return value description#>
*/
- (BOOL) isValidPassword:(NSString* _Nonnull) password;
/**
* <#Description#>
*/
- (void) logout;
- (BOOL) isValidUser;
/**
* <#Description#>
*
* @return <#return value description#>
*/
- (BOOL) hasValidUserAndPasswordData;
/**
* <#Description#>
*
* @param success <#success description#>
* @param failure <#failure description#>
*/
- (void) registerCurrentUserWithBlockSuccess:(nullable void (^)(id _Nullable responseObject))success
failure:(nullable void (^)(NSError * _Nonnull error))failure;
/**
* <#Description#>
*
* @return <#return value description#>
*/
- (BOOL) autenticated;
//- (void) setPassword:(NSString * _Nonnull)password inBackGroundWithBlock:(nullable void (^)(BOOL saveStatus, id responseObject, NSError * error)) responseBlock;
@@ -93,6 +115,10 @@
* <#Description#>
*/
@property (nonatomic, strong, nullable) NSString * password;
/**
* <#Description#>
*/
@property (nonatomic, strong, nullable) NSString * confirmPassword;
/**
* <#Description#>
*/
+41 -10
View File
@@ -10,6 +10,7 @@
#import "NSString+Helper.h"
#import "PNObjectConstants.h"
#import "PNObject+Protected.h"
#import "PNObject+PNObjectConnection.h"
@interface PNUser() <PNObjectSubclassing>
@@ -30,10 +31,10 @@ static bool isFirstAccess = YES;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
isFirstAccess = NO;
SINGLETON = [[super allocWithZone:NULL] initForCurrentUser];
});
return SINGLETON;
}
@@ -57,16 +58,16 @@ static bool isFirstAccess = YES;
if (isFirstAccess) {
[self doesNotRecognizeSelector:_cmd];
}
NSDictionary *savedUser = [[PNObjectModel sharedInstance] fetchObjectsWithClass:[self class]];
if (savedUser) {
self = [super initWithJSON:savedUser];
}
else {
self = [super init];
}
if (self) {
}
return self;
@@ -90,6 +91,20 @@ static bool isFirstAccess = YES;
}
}
- (void) setConfirmPassword:(NSString *)confirmPassword {
if ([self isValidPassword:confirmPassword]) {
if ([confirmPassword isEqualToString:_password]) {
_confirmPassword = confirmPassword;
}
else {
NSLogDebug(@"Inserted Passord is not same password.");
}
}
else {
NSLogDebug(@"Inserted Passord is not valid.Lenght must be >= %ld",(long)[[PNObjectConfig sharedInstance] minPasswordLenght]);
}
}
- (BOOL) isValidPassword:(NSString* _Nonnull) password {
if ([password length] >= [[PNObjectConfig sharedInstance] minPasswordLenght]) {
return YES;
@@ -102,18 +117,33 @@ static bool isFirstAccess = YES;
[self resetObject];
}
- (BOOL) isValidUser {
- (BOOL) hasValidUserAndPasswordData {
if(self.username && self.password && [self isValidPassword:[self password]]){
return YES;
}
return NO;
}
#pragma mark PNObjectSubclassing Protocol
- (void) registerCurrentUserWithBlockSuccess:(nullable void (^)(id _Nullable responseObject))success
failure:(nullable void (^)(NSError * _Nonnull error))failure {
[self POSTWithEndpointAction:@"registration/register" Progress:nil success:^(NSURLSessionDataTask * _Nullable task, PNObject * _Nullable responseObject) {
NSLog(@"response %@",responseObject);
if(success){
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
}];
}
#pragma mark PNObjectSubclassing Protocol
+ (NSDictionary *)objcetMapping {
NSDictionary *mapping = @{
@"userId":@"id",
@"firstName":@"firstName",
@@ -122,7 +152,8 @@ static bool isFirstAccess = YES;
@"sex":@"sex",
@"birthDate":@"birthDate",
@"phone":@"phone",
@"password":@"password",
@"password":@"plainPassword[first]",
@"confirmPassword":@"plainPassword[second]",
@"hasAcceptedPrivacy":@"hasAcceptedPrivacy",
@"hasAcceptedNewsletter":@"hasAcceptedNewsletter",
@"hasVerifiedEmail":@"hasVerifiedEmail",
+17 -3
View File
@@ -10,8 +10,22 @@
@interface PNObject (PNObjectConnection)
+ (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;
+ (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
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
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error))failure;
@end
+113 -26
View File
@@ -16,58 +16,145 @@
@implementation PNObject (PNObjectConnection)
+ (NSURLSessionDataTask * _Nonnull) GETWithProgress:(nullable void (^)(NSProgress * _Nonnull downloadProgress)) downloadProgress
+ (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 {
return [[[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);
}
}];
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, PNObject * _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);
}
} 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) 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
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 = [[[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 POSTWithEndpointAction:endPoint Progress:uploadProgress success:success failure:failure];
} failure:^(NSError * _Nonnull error) {
}];
}
}
/*+ (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);
+256 -263
View File
@@ -19,291 +19,284 @@
@dynamic singleInstance;
+ (NSArray * _Nonnull) protectedProperties {
return @[@"JSON",@"objectModel",@"objectMapping",@"singleInstance"];
return @[@"JSON",@"objectModel",@"objectMapping",@"singleInstance"];
}
- (void)populateObjectFromJSON:(id _Nullable)JSON
{
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];
}
for(NSString *propertyName in properties) {
if([propertyName isEqualToString:@"mappingError"])
continue;
NSString *mappedJSONKey;
NSString *mappedJSONType;
NSString *propertyType = [properties valueForKey:propertyName];
NSLogDebug(@"%@",self.JSONObject);
NSLogDebug(@"%@",[[self class] objcetMapping]);
id mappingValue = [[[self class] objcetMapping] valueForKey:propertyName];
if([mappingValue isKindOfClass:NSDictionary.class]) {
mappedJSONKey = [mappingValue valueForKey:@"key"];
mappedJSONType = [mappingValue valueForKey:@"type"];
} else {
mappedJSONKey = mappingValue;
}
if ([[PNObject protectedProperties] containsObject:propertyName]) {
continue;
}
// Get JSON value for the mapped key
id value = [JSON valueForKeyPath:mappedJSONKey];
((void (^)())@{
@"c" : ^{
char val = [value charValue];
[self setValue:@(val) forKey:propertyName];
},
@"d" : ^{
double val = [value doubleValue];
[self setValue:@(val) forKey:propertyName];
},
@"f" : ^{
float val = [value floatValue];
[self setValue:@(val) forKey:propertyName];
},
@"i" : ^{
int val = [value intValue];
[self setValue:@(val) forKey:propertyName];
},
@"l" : ^{
long val = [value longValue];
[self setValue:@(val) forKey:propertyName];
},
@"s" : ^{
short val = [value shortValue];
[self setValue:@(val) forKey:propertyName];
},
@"B" : ^{
BOOL val = [value boolValue];
[self setValue:@(val) forKey:propertyName];
},
@"NSString" : ^{
if (![self isObjNull:value]) {
[self setValue:value forKey:propertyName];
}
},
@"NSNumber" : ^{
NSInteger val = [value integerValue];
[self setValue:@(val) forKey:propertyName];
},
@"NSDate" : ^{
NSString *str = [NSString stringWithFormat:@"%@", value];
NSDate *val = [[NSDate dateFromString:str withFormat:kNSDateHelperFormatSQLDateWithTime] toLocalTime];
if (![self isObjNull:val]) {
[self setValue:val forKey:propertyName];
}
},
@"NSArray" : ^{
NSMutableArray *arr = [NSMutableArray array];
for(id JSONObject in value) {
PNObject *val = [[NSClassFromString(mappedJSONType) alloc] initWithJSON:JSONObject];
[arr addObject:val];
}
[self setValue:arr forKey:propertyName];
},
@"NSMutableArray" : ^{
NSMutableArray *arr = [NSMutableArray array];
for(id JSONObject in value) {
PNObject *val = [[NSClassFromString(mappedJSONType) alloc] initWithJSON:JSONObject];
[arr addObject:val];
}
[self setValue:arr forKey:propertyName];
}
}[propertyType] ?: ^{
BOOL isPNObjectSubclass = [NSClassFromString(propertyType) isSubclassOfClass:[PNObject class]];
if(isPNObjectSubclass) {
PNObject *val = [[NSClassFromString(propertyType) alloc] initWithJSON:value];
[self setValue:val forKey:propertyName];
}
else {
NSString *errorStr = [NSString stringWithFormat:@"Property '%@' could not be assigned any value.", propertyName];
NSLogDebug(@"%@",errorStr);
}
})();
}
NSDictionary *properties = [PNObject propertiesForClass:self.class];
for(NSString *propertyName in properties) {
if([propertyName isEqualToString:@"mappingError"])
continue;
NSString *mappedJSONKey;
NSString *mappedJSONType;
NSString *propertyType = [properties valueForKey:propertyName];
NSLogDebug(@"%@",self.JSONObject);
NSLogDebug(@"%@",[[self class] objcetMapping]);
id mappingValue = [[[self class] objcetMapping] valueForKey:propertyName];
if([mappingValue isKindOfClass:NSDictionary.class]) {
mappedJSONKey = [mappingValue valueForKey:@"key"];
mappedJSONType = [mappingValue valueForKey:@"type"];
} else {
mappedJSONKey = mappingValue;
}
if ([[PNObject protectedProperties] containsObject:propertyName]) {
continue;
}
// Get JSON value for the mapped key
id value = [JSON valueForKeyPath:mappedJSONKey];
((void (^)())@{
@"c" : ^{
char val = [value charValue];
[self setValue:@(val) forKey:propertyName];
},
@"d" : ^{
double val = [value doubleValue];
[self setValue:@(val) forKey:propertyName];
},
@"f" : ^{
float val = [value floatValue];
[self setValue:@(val) forKey:propertyName];
},
@"i" : ^{
int val = [value intValue];
[self setValue:@(val) forKey:propertyName];
},
@"l" : ^{
long val = [value longValue];
[self setValue:@(val) forKey:propertyName];
},
@"s" : ^{
short val = [value shortValue];
[self setValue:@(val) forKey:propertyName];
},
@"B" : ^{
BOOL val = [value boolValue];
[self setValue:@(val) forKey:propertyName];
},
@"NSString" : ^{
if (![self isObjNull:value]) {
[self setValue:value forKey:propertyName];
}
},
@"NSNumber" : ^{
NSInteger val = [value integerValue];
[self setValue:@(val) forKey:propertyName];
},
@"NSDate" : ^{
NSString *str = [NSString stringWithFormat:@"%@", value];
NSDate *val = [[NSDate dateFromString:str withFormat:kNSDateHelperFormatSQLDateWithTime] toLocalTime];
if (![self isObjNull:val]) {
[self setValue:val forKey:propertyName];
}
},
@"NSArray" : ^{
NSMutableArray *arr = [NSMutableArray array];
for(id JSONObject in value) {
PNObject *val = [[NSClassFromString(mappedJSONType) alloc] initWithJSON:JSONObject];
[arr addObject:val];
}
[self setValue:arr forKey:propertyName];
},
@"NSMutableArray" : ^{
NSMutableArray *arr = [NSMutableArray array];
for(id JSONObject in value) {
PNObject *val = [[NSClassFromString(mappedJSONType) alloc] initWithJSON:JSONObject];
[arr addObject:val];
}
[self setValue:arr forKey:propertyName];
}
}[propertyType] ?: ^{
BOOL isPNObjectSubclass = [NSClassFromString(propertyType) isSubclassOfClass:[PNObject class]];
if(isPNObjectSubclass) {
PNObject *val = [[NSClassFromString(propertyType) alloc] initWithJSON:value];
[self setValue:val forKey:propertyName];
}
else {
NSString *errorStr = [NSString stringWithFormat:@"Property '%@' could not be assigned any value.", propertyName];
NSLogDebug(@"%@",errorStr);
}
})();
}
}
- (void)resetObject
{
NSDictionary *properties = [PNObject propertiesForClass:self.class];
for(NSString *propertyName in properties) {
if([propertyName isEqualToString:@"mappingError"])
continue;
NSString *mappedJSONKey;
NSString *mappedJSONType;
NSString *propertyType = [properties valueForKey:propertyName];
id mappingValue = [self.JSONObject valueForKey:propertyName];
if([mappingValue isKindOfClass:NSDictionary.class]) {
mappedJSONKey = [mappingValue valueForKey:@"key"];
mappedJSONType = [mappingValue valueForKey:@"type"];
} else {
mappedJSONKey = mappingValue;
}
if ([[PNObject protectedProperties] containsObject:propertyName]
|| [propertyName isEqualToString:@"description"]
|| [propertyName isEqualToString:@"debugDescription"]) {
continue;
}
// Get JSON value for the mapped key
((void (^)())@{
@"c" : ^{
char val = '\0';
[self setValue:@(val) forKey:propertyName];
},
@"d" : ^{
double val = 0.0;
[self setValue:@(val) forKey:propertyName];
},
@"f" : ^{
float val = 0.0;
[self setValue:@(val) forKey:propertyName];
},
@"i" : ^{
int val = 0;
[self setValue:@(val) forKey:propertyName];
},
@"l" : ^{
long val = 0;
[self setValue:@(val) forKey:propertyName];
},
@"s" : ^{
short val = 0;
[self setValue:@(val) forKey:propertyName];
},
@"B" : ^{
[self setValue:@(NO) forKey:propertyName];
},
@"NSString" : ^{
[self setValue:[[NSString alloc] init] forKey:propertyName];
},
@"NSNumber" : ^{
[self setValue:[[NSNumber alloc] init] forKey:propertyName];
},
@"NSDate" : ^{
[self setValue:[[NSDate alloc] init] forKey:propertyName];
},
@"NSArray" : ^{
[self setValue:[[NSArray alloc] init] forKey:propertyName];
},
@"NSMutableArray" : ^{
[self setValue:[[NSMutableArray alloc] init] forKey:propertyName];
}
}[propertyType] ?: ^{
BOOL isPNObjectSubclass = [NSClassFromString(propertyType) isSubclassOfClass:[PNObject class]];
if(isPNObjectSubclass) {
[self setValue:@"" forKey:propertyName];
}
else {
NSString *errorStr = [NSString stringWithFormat:@"Property '%@' could not be assigned any value.", propertyName];
NSLogDebug(@"%@",errorStr);
}
})();
}
NSDictionary *properties = [PNObject propertiesForClass:self.class];
for(NSString *propertyName in properties) {
if([propertyName isEqualToString:@"mappingError"])
continue;
NSString *mappedJSONKey;
NSString *mappedJSONType;
NSString *propertyType = [properties valueForKey:propertyName];
id mappingValue = [self.JSONObject valueForKey:propertyName];
if([mappingValue isKindOfClass:NSDictionary.class]) {
mappedJSONKey = [mappingValue valueForKey:@"key"];
mappedJSONType = [mappingValue valueForKey:@"type"];
} else {
mappedJSONKey = mappingValue;
}
if ([[PNObject protectedProperties] containsObject:propertyName]
|| [propertyName isEqualToString:@"description"]
|| [propertyName isEqualToString:@"debugDescription"]) {
continue;
}
// Get JSON value for the mapped key
((void (^)())@{
@"c" : ^{
char val = '\0';
[self setValue:@(val) forKey:propertyName];
},
@"d" : ^{
double val = 0.0;
[self setValue:@(val) forKey:propertyName];
},
@"f" : ^{
float val = 0.0;
[self setValue:@(val) forKey:propertyName];
},
@"i" : ^{
int val = 0;
[self setValue:@(val) forKey:propertyName];
},
@"l" : ^{
long val = 0;
[self setValue:@(val) forKey:propertyName];
},
@"s" : ^{
short val = 0;
[self setValue:@(val) forKey:propertyName];
},
@"B" : ^{
[self setValue:@(NO) forKey:propertyName];
},
@"NSString" : ^{
[self setValue:[[NSString alloc] init] forKey:propertyName];
},
@"NSNumber" : ^{
[self setValue:[[NSNumber alloc] init] forKey:propertyName];
},
@"NSDate" : ^{
[self setValue:[[NSDate alloc] init] forKey:propertyName];
},
@"NSArray" : ^{
[self setValue:[[NSArray alloc] init] forKey:propertyName];
},
@"NSMutableArray" : ^{
[self setValue:[[NSMutableArray alloc] init] forKey:propertyName];
}
}[propertyType] ?: ^{
BOOL isPNObjectSubclass = [NSClassFromString(propertyType) isSubclassOfClass:[PNObject class]];
if(isPNObjectSubclass) {
[self setValue:@"" forKey:propertyName];
}
else {
NSString *errorStr = [NSString stringWithFormat:@"Property '%@' could not be assigned any value.", propertyName];
NSLogDebug(@"%@",errorStr);
}
})();
}
}
- (BOOL)isObjNull:(id _Nullable)obj
{
if(!obj || nil == obj || NSNull.null == obj || ([obj isKindOfClass:[NSString class]] && [obj isEqualToString:@"(null)"]) || [obj isEqual:[NSNull null]])
return YES;
else
return NO;
if(!obj || nil == obj || NSNull.null == obj || ([obj isKindOfClass:[NSString class]] && [obj isEqualToString:@"(null)"]) || [obj isEqual:[NSNull null]])
return YES;
else
return NO;
}
static BOOL property_getTypeString( objc_property_t property, char *buffer )
{
const char * attrs = property_getAttributes( property );
if ( attrs == NULL )
return NO;
const char * e = strchr( attrs, ',' );
if ( e == NULL )
return NO;
int len = (int)(e - attrs);
memcpy( buffer, attrs, len );
buffer[len] = '\0';
return YES;
const char * attrs = property_getAttributes( property );
if ( attrs == NULL )
return NO;
const char * e = strchr( attrs, ',' );
if ( e == NULL )
return NO;
int len = (int)(e - attrs);
memcpy( buffer, attrs, len );
buffer[len] = '\0';
return YES;
}
+ (NSDictionary *)propertiesForClass:(Class)PNObjClass
{
if (PNObjClass == NULL) {
return nil;
}
NSMutableDictionary *results = [NSMutableDictionary dictionary];
if ([PNObjClass isSubclassOfClass:[PNObject class]] && PNObjClass != [PNObject class]) {
[results addEntriesFromDictionary:[self propertiesForClass:[PNObject class]]];
}
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(PNObjClass, &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char *propName = property_getName(property);
if(propName) {
//const char *propType = getPropertyType(property);
char propType[256];
if (!property_getTypeString(property, propType)) {
continue;
}
NSString *propertyName = [NSString stringWithUTF8String:propName];
NSString *propertyType = [NSString stringWithUTF8String:propType];
NSRange range = [propertyType rangeOfString:@"T@\""];
NSRange range2 = [propertyType rangeOfString:@"T"];
if (range.location != NSNotFound) {
NSRange subStrRange = NSMakeRange(range.length, propertyType.length - (range.length + 1));
propertyType = [propertyType substringWithRange:subStrRange];
}
else if (range2.location != NSNotFound) {
NSRange subStrRange = NSMakeRange(range2.length, propertyType.length - (range2.length));
propertyType = [propertyType substringWithRange:subStrRange];
}
//NSLogDebug(@"Prop type & name: %@ -- %@", propertyType, propertyName);
if (![[PNObject protectedProperties] containsObject:propertyName]) {
[results setObject:propertyType forKey:propertyName];
}
}
}
free(properties);
// returning a copy here to make sure the dictionary is immutable
return [NSDictionary dictionaryWithDictionary:results];
if (PNObjClass == NULL) {
return nil;
}
NSMutableDictionary *results = [NSMutableDictionary dictionary];
if ([PNObjClass isSubclassOfClass:[PNObject class]] && PNObjClass != [PNObject class]) {
[results addEntriesFromDictionary:[self propertiesForClass:[PNObject class]]];
}
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(PNObjClass, &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char *propName = property_getName(property);
if(propName) {
//const char *propType = getPropertyType(property);
char propType[256];
if (!property_getTypeString(property, propType)) {
continue;
}
NSString *propertyName = [NSString stringWithUTF8String:propName];
NSString *propertyType = [NSString stringWithUTF8String:propType];
NSRange range = [propertyType rangeOfString:@"T@\""];
NSRange range2 = [propertyType rangeOfString:@"T"];
if (range.location != NSNotFound) {
NSRange subStrRange = NSMakeRange(range.length, propertyType.length - (range.length + 1));
propertyType = [propertyType substringWithRange:subStrRange];
}
else if (range2.location != NSNotFound) {
NSRange subStrRange = NSMakeRange(range2.length, propertyType.length - (range2.length));
propertyType = [propertyType substringWithRange:subStrRange];
}
//NSLogDebug(@"Prop type & name: %@ -- %@", propertyType, propertyName);
if (![[PNObject protectedProperties] containsObject:propertyName]) {
[results setObject:propertyType forKey:propertyName];
}
}
}
free(properties);
// returning a copy here to make sure the dictionary is immutable
return [NSDictionary dictionaryWithDictionary:results];
}
@end
+3
View File
@@ -38,6 +38,8 @@
- (BOOL) autoRemoveLocally;
- (NSDictionary * _Nonnull) JSONFormObject;
///--------------------------------------
#pragma mark - PNObject Properties
///--------------------------------------
@@ -55,4 +57,5 @@
*/
@property (nonatomic, strong, nonnull) NSDictionary * JSONObject;
@end
+300 -265
View File
@@ -35,334 +35,369 @@
#pragma mark PNObjectSubclassing
+ (NSDictionary *) objcetMapping {
NSDictionary *mapping = @{@"objID":@"objID",
@"createdAt":@"created_at",
};
return mapping;
NSDictionary *mapping = @{@"objID":@"objID",
@"createdAt":@"created_at",
};
return mapping;
}
+ (NSString *)objectEndPoint {
return NSStringFromClass([self class]);
return NSStringFromClass([self class]);
}
+ (BOOL) singleInstance {
return NO;
return NO;
}
+ (NSString*) objectClassName {
return NSStringFromClass([self class]);
return NSStringFromClass([self class]);
}
#pragma mark -
+ (NSString * _Nonnull) PNObjClassName {
if ([[self class] resolveClassMethod:@selector(objectClassName)]) {
return [[self class] objectClassName];
}
else {
return [[super class] objectClassName];
}
if ([[self class] resolveClassMethod:@selector(objectClassName)]) {
return [[self class] objectClassName];
}
else {
return [[super class] objectClassName];
}
}
+ (NSString * _Nonnull) PNObjEndPoint {
if ([[self class] resolveClassMethod:@selector(objectEndPoint)]) {
return [[self class] objectEndPoint];
}
else {
return [[super class] objectEndPoint];
}
if ([[self class] resolveClassMethod:@selector(objectEndPoint)]) {
return [[self class] objectEndPoint];
}
else {
return [[super class] objectEndPoint];
}
}
- (_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];
}
}
return self;
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;
}
[self addObserver:self forKeyPath:propertyName options:NSKeyValueObservingOptionNew context:nil];
}
}
return self;
}
- (_Nullable instancetype) initWithJSON:( NSDictionary * _Nonnull) JSON {
self = [super init];
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];
}
NSAssert(_JSONObject, @"You must create objectMapping");
_JSON = [[NSMutableDictionary alloc] initWithDictionary:JSON];
[self populateObjectFromJSON:_JSON];
}
return self;
self = [super init];
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;
}
- (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];
[JSON setValue:@(val) forKey:propertyName];
},
@"d" : ^{
double val = [value doubleValue];
[JSON setValue:@(val) forKey:propertyName];
},
@"f" : ^{
float val = [value floatValue];
[JSON setValue:@(val) forKey:propertyName];
},
@"i" : ^{
int val = [value intValue];
[JSON setValue:@(val) forKey:propertyName];
},
@"l" : ^{
long val = [value longValue];
[JSON setValue:@(val) forKey:propertyName];
},
@"s" : ^{
short val = [value shortValue];
[JSON setValue:@(val) forKey:propertyName];
},
@"B" : ^{
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];
}
},
@"NSString" : ^{
NSString *val = [NSString stringWithFormat:@"%@", value];
if (![self isObjNull:val]) {
[JSON setValue:val forKey:propertyName];
}
},
@"NSNumber" : ^{
NSInteger val = [value integerValue];
[JSON setValue:@(val) forKey:propertyName];
},
@"NSDate" : ^{
NSDate *val = [value toLocalTime];
if (![self isObjNull:val]) {
[JSON setValue:val forKey:propertyName];
}
},
@"NSArray" : ^{
NSMutableArray *arr = [NSMutableArray array];
for(id PNObject in value) {
SEL selector = NSSelectorFromString(@"JSONObject");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature: [[PNObject class] instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:PNObject];
[invocation invoke];
NSDictionary *returnValue;
[invocation getReturnValue:&returnValue];
[arr addObject:returnValue];
}
[JSON setValue:arr forKey:propertyName];
},
@"NSMutableArray" : ^{
NSMutableArray *arr = [NSMutableArray array];
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];
[invocation setTarget:value];
[invocation invoke];
NSDictionary *returnValue;
[invocation getReturnValue:&returnValue];
}
[JSON setValue:arr forKey:propertyName];
}
}[propertyType] ?: ^{
BOOL isPNObjectSubclass = [NSClassFromString(propertyType) isSubclassOfClass:[PNObject class]];
if(isPNObjectSubclass) {
SEL selector = NSSelectorFromString(@"JSONObject");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[PNObject class] instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:value];
[invocation invoke];
NSDictionary *returnValue;
[invocation getReturnValue:&returnValue];
[JSON setValue:returnValue forKey:propertyName];
}
else {
// do nothing
}
})();
}
_JSON = JSON;
return _JSON;
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];
[JSON setValue:@(val) forKey:propertyName];
},
@"d" : ^{
double val = [value doubleValue];
[JSON setValue:@(val) forKey:propertyName];
},
@"f" : ^{
float val = [value floatValue];
[JSON setValue:@(val) forKey:propertyName];
},
@"i" : ^{
int val = [value intValue];
[JSON setValue:@(val) forKey:propertyName];
},
@"l" : ^{
long val = [value longValue];
[JSON setValue:@(val) forKey:propertyName];
},
@"s" : ^{
short val = [value shortValue];
[JSON setValue:@(val) forKey:propertyName];
},
@"B" : ^{
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];
}
},
@"NSString" : ^{
NSString *val = [NSString stringWithFormat:@"%@", value];
if (![self isObjNull:val]) {
[JSON setValue:val forKey:propertyName];
}
},
@"NSNumber" : ^{
NSInteger val = [value integerValue];
[JSON setValue:@(val) forKey:propertyName];
},
@"NSDate" : ^{
NSDate *val = [value toLocalTime];
if (![self isObjNull:val]) {
[JSON setValue:val forKey:propertyName];
}
},
@"NSArray" : ^{
NSMutableArray *arr = [NSMutableArray array];
for(id PNObject in value) {
SEL selector = NSSelectorFromString(@"JSONObject");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature: [[PNObject class] instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:PNObject];
[invocation invoke];
NSDictionary *returnValue;
[invocation getReturnValue:&returnValue];
[arr addObject:returnValue];
}
[JSON setValue:arr forKey:propertyName];
},
@"NSMutableArray" : ^{
NSMutableArray *arr = [NSMutableArray array];
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];
[invocation setTarget:value];
[invocation invoke];
NSDictionary *returnValue;
[invocation getReturnValue:&returnValue];
}
[JSON setValue:arr forKey:propertyName];
}
}[propertyType] ?: ^{
BOOL isPNObjectSubclass = [NSClassFromString(propertyType) isSubclassOfClass:[PNObject class]];
if(isPNObjectSubclass) {
SEL selector = NSSelectorFromString(@"JSONObject");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[PNObject class] instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:value];
[invocation invoke];
NSDictionary *returnValue;
[invocation getReturnValue:&returnValue];
[JSON setValue:returnValue forKey:propertyName];
}
else {
// do nothing
}
})();
}
_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]];
}
}
return JSONFormObject;
}
- (NSDictionary* _Nonnull) JSONObject {
if (!_JSON) {
return [self reverseMapping];
}
else {
return _JSON;
}
if (!_JSON) {
return [self reverseMapping];
}
else {
return _JSON;
}
}
- (NSString* _Nonnull) description {
if (!_JSON) {
[self reverseMapping];
}
return [_JSON description];
if (!_JSON) {
[self reverseMapping];
}
return [_JSON description];
}
- (void) setSingleInstance:(BOOL)singleInstance {
_singleInstance = singleInstance;
_singleInstance = singleInstance;
}
#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]) {
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);
NSLogDebug(@"Create directory error: %@", error);
#endif
return NO;
}
}
return NO;
}
}
#ifdef DEBUG
NSLogDebug(@"%@",[docDir stringByAppendingFormat:@"/%@",PNOBJECT_DIR]);
NSLogDebug(@"%@",[docDir stringByAppendingFormat:@"/%@",PNOBJECT_DIR]);
#endif
return YES;
return YES;
}
- (id _Nonnull) saveLocally {
__weak id weakSelf = self;
return [_objectModel saveLocally:weakSelf];
__weak id weakSelf = self;
return [_objectModel saveLocally:weakSelf];
}
- (BOOL) autoRemoveLocally {
return [_objectModel removeObjectLocally:self];
return [_objectModel removeObjectLocally:self];
}
#pragma mark -
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
[_JSON setObject:[change objectForKey:@"new"] forKey:[[[self class] objcetMapping] objectForKey:keyPath]];
[_JSON setObject:[change objectForKey:@"new"] forKey:[[[self class] objcetMapping] objectForKey:keyPath]];
}
- (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;
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;
}
+39 -1
View File
@@ -8,6 +8,7 @@
#import <Foundation/Foundation.h>
#import <AFNetworking/AFNetworking.h>
#import "HTTPStatusCodes.h"
#import "AFOAuth2Manager.h"
#import "AFHTTPRequestSerializer+OAuth2.h"
@@ -112,6 +113,38 @@ extern NSString* _Nonnull const Client_Secret;
*/
- (void) setAcceptablePasswordLenght:(NSUInteger) passLenght;
/**
* <#Description#>
*/
- (void) refreshTokenForClientCredential;
/**
* <#Description#>
*
* @param success <#success description#>
* @param failure <#failure description#>
*/
- (void) refreshTokenForClientCredentialWithBlockSuccess:(nullable void (^)(BOOL refreshSuccess))success
failure:(nullable void (^)(NSError * _Nonnull error))failure;
/**
* <#Description#>
*/
- (void) refreshTokenForUser;
/**
* <#Description#>
*
* @param success <#success description#>
* @param failure <#failure description#>
*/
- (void) refreshTokenForUserWithBlockSuccess:(nullable void (^)(BOOL refreshSuccess))success
failure:(nullable void (^)(NSError * _Nonnull error))failure;
/**
* <#Description#>
*/
- (BOOL) resetToken;
///--------------------------------------
#pragma mark - PNObjectConfig Properties
@@ -119,7 +152,12 @@ extern NSString* _Nonnull const Client_Secret;
/**
* <#Description#>
*/
@property (nonatomic, strong) AFOAuth2Manager *manager;
@property (nonatomic, strong, nonnull) AFOAuth2Manager *manager;
/**
* <#Description#>
*/
@property (nonatomic, strong, nullable, readonly) AFOAuthCredential *currentOauthCredential;
/**
* <#Description#>
+59 -17
View File
@@ -35,8 +35,6 @@ NSString* const Client_Secret = @"client_secret";
@property (nonatomic) BOOL oauthEnabled;
@property (nonatomic, strong) AFOAuthCredential *currentOauthCredential;
@property (nonatomic, strong) NSMutableDictionary *configuration;
@property (nonatomic, strong) NSMutableDictionary *headerFields;
@property (nonatomic) Environment currentEnv;
@@ -193,6 +191,8 @@ static bool isFirstAccess = YES;
_manager = [AFOAuth2Manager manager];
}
_currentOauthCredential = [AFOAuthCredential retrieveCredentialWithIdentifier:PNObjectServiceCredentialIdentifier];
if (_oauthEnabled && _currentOAuthClientID && _currentOAuthClientSecret) {
if (![_manager clientID]) {
@@ -211,38 +211,80 @@ static bool isFirstAccess = YES;
if (canTryRefreh) {
if (!_currentOauthCredential) {
[self tryRefreshToken];
if (_currentOauthCredential && ![_currentOauthCredential isExpired]) {
[[_manager requestSerializer] setAuthorizationHeaderFieldWithCredential:_currentOauthCredential];
}
else {
[[_manager requestSerializer] setAuthorizationHeaderFieldWithCredential:_currentOauthCredential];
[self refreshTokenForClientCredential];
}
}
return _manager;
}
- (void) tryRefreshToken {
if ([PNUser currentUser] && [[PNUser currentUser] isValidUser]) {
- (BOOL) resetToken {
if (_currentOauthCredential) {
return [AFOAuthCredential deleteCredentialWithIdentifier:PNObjectServiceCredentialIdentifier];
}
return NO;
}
- (void) refreshTokenForUser {
[self refreshTokenForUserWithBlockSuccess:nil failure:nil];
}
- (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) {
_currentOauthCredential = credential;
[AFOAuthCredential storeCredential:_currentOauthCredential withIdentifier:PNObjectServiceCredentialIdentifier];
[_manager.requestSerializer setAuthorizationHeaderFieldWithCredential:_currentOauthCredential];
if (success) {
success(YES);
}
} failure:^(NSError * _Nonnull error) {
[[NSNotificationCenter defaultCenter] postNotificationName:PNObjectLocalNotificationRefreshTokenUserFail object:error];
}];
}
else {
[_manager authenticateUsingOAuthWithURLString:[_currentEndPointBaseUrl stringByAppendingString:@"oauth-token"] scope:nil success:^(AFOAuthCredential * _Nonnull credential) {
_currentOauthCredential = credential;
[_manager.requestSerializer setAuthorizationHeaderFieldWithCredential:_currentOauthCredential];
} failure:^(NSError * _Nonnull error) {
[[NSNotificationCenter defaultCenter] postNotificationName:PNObjectLocalNotificationRefreshTokenClientCredentialFail object:error];
if (failure) {
failure(error);
}
}];
}
}
- (void) refreshTokenForClientCredential {
[self refreshTokenForClientCredentialWithBlockSuccess:nil failure:nil];
}
- (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) {
success(YES);
}
} failure:^(NSError * _Nonnull error) {
[[NSNotificationCenter defaultCenter] postNotificationName:PNObjectLocalNotificationRefreshTokenClientCredentialFail object:error];
if (failure) {
failure(error);
}
}];
}
- (void) setAcceptablePasswordLenght:(NSUInteger) passLenght {
_minPasswordLenght = passLenght;
}