存储iPhone日历应用程序数据的最佳方式

时间:2016-06-16 23:54:25

标签: ios objective-c iphone

我正在开发一款iPhone应用程序。它是我的代理商的企业日历应用程序。我们有一个RESTful API后端连接到输入约会的Web应用程序。个人的约会将显示在该用户的iPhone上。数据由XML发送。每天只有3或4个约会,每个记录少于10个字段,因此一次不会传输大量数据(只是所选日期的信息)。

我尝试在iPhone上使用数组来设计解析数据,但是Web服务器上的安全检查会在加载数据时使应用程序超时,而且我没有很好地处理异步处理。

现在我想知道我是否正确地接近了这个问题。使用Core Data存储约会然后在后台更新Core Data存储会更好吗?我知道我需要在加载表进程之外更新数据。对于解决这个问题的最佳方法,我感到很茫然。

我查看了网站,了解如何处理此问题。我试过看书。任何帮助将不胜感激。

Security.h

typedef void (^touchIDComplete)(BOOL);
typedef void (^fileExists)(BOOL);
typedef void (^sessionVerify)(BOOL);
typedef void (^parsingData)(BOOL);
typedef void (^touchIDSuccess)(BOOL);
typedef void (^sessionRetrieved)(BOOL);
typedef void (^touchIDComplete)(BOOL);
typedef void (^sessionReading)(BOOL);
typedef void (^fillArray)(BOOL);
typedef void (^getTheData)(NSData *myData, NSError *error);
typedef void (^gettingESNBlock)(NSString *myESN, NSString *newSession, BOOL success, NSError *error);
typedef void (^checkingESNBlock)(NSString *myESN, NSString *sessionInfo, BOOL success, NSError *error);


@interface Security : NSObject

@property (strong, nonatomic) NSArray *types;
@property (strong, nonatomic) NSArray *esn;
@property (strong, nonatomic) NSString *idfv;
@property (strong, nonatomic) NSData *parseData;
@property (strong, nonatomic) NSString *sessionDetail;
@property (strong, nonatomic) NSString *loginFinished;
@property (strong, nonatomic) NSMutableURLRequest *request;
@property (atomic) NSString *passESN;

- (void)waitForData:(sessionVerify)compblock;
- (void)waitForFile:(fileExists)compblock;
- (void)waitForESN:(parsingData)compblock;
- (void)findESN:(gettingESNBlock)callback;
- (void)checkThumb:(touchIDSuccess)compblock;
- (void)readIt:(sessionRetrieved)compblock;
- (void)readNewSession:(sessionReading)compblock;
- (void)doTheWork:(NSString *)theESN withSession:(NSString *)newSession withSuccess:(BOOL)success error:(NSError *)error;
- (void)checkESN:(checkingESNBlock)callback;
- (void)checkTheSession:(NSString *)oldESN withSession:(NSString *)oldSession withSuccess:(BOOL)success error:(NSError *)error;
- (void)fillAppointmentData:(fillArray)compblock;
- (void)gettingData:(getTheData)compblock;

@end

Security.m

@implementation Security

void(^getESNForCallback)(NSString *myESN, NSString *newSession, BOOL success, NSError *error);
void(^checkESNWithCallback)(NSString *myESN, NSString *oldSession, BOOL success, NSError *error);

- (void)waitForFile:(fileExists) compblock {

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
    NSString *fullPath = [documentsDirectoryPath stringByAppendingString:@"/session.txt"];
    compblock([fileManager fileExistsAtPath:fullPath]);
}

- (void) waitForData:(sessionVerify) compblock {
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:self.request
                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

                                            if (error) {
                                                return;
                                            }

                                            if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                                NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];

                                                if (statusCode != 200) {
                                                    if (statusCode == 401) {
                                                        // Insert process for thumbprint and session cookie pull
                                                        NSFileManager *fileManagerThree = [NSFileManager defaultManager];
                                                        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                                                        NSString *sessionPath = [documentsPath stringByAppendingPathComponent:@"session.txt"];
                                                        NSError *error;
                                                        BOOL success = [fileManagerThree removeItemAtPath:sessionPath error:&error];
                                                        if (success) {
                                                        } else {
                                                        }
                                                    } else {
                                                        return;
                                                    }
                                                }
                                            }
                                            self.parseData = data;
                                            compblock (YES);
                                        }];
    [task resume];
}

- (void)waitForESN:(parsingData) compblock {
    ParseTypeXML *myParser = [[ParseTypeXML alloc] initWithData:self.parseData];
    VariableStore *globals = [VariableStore sharedInstance];
    if ([myParser.esn count] == 0) {
        globals.user_esn = @"Error";
        compblock(YES);
    } else {
        globals.user_esn = myParser.esn[0];
        compblock(YES);
    }
}

- (void)findESN:(gettingESNBlock)callback {
    getESNForCallback = callback;
    VariableStore *globals = [VariableStore sharedInstance];
    [self doTheWork:globals.user_esn withSession:globals.sessionInfo withSuccess:YES error:nil];
}

- (void)doTheWork:(NSString *)theESN withSession:(NSString *)newSession withSuccess:(BOOL)success error:(NSError *)error {
    [self checkThumb:^(BOOL finished) {
        if(finished) {
            [self readIt:^(BOOL newFile) {
                if (newFile) {
                    [self readNewSession:^(BOOL seen) {
                        if (seen) {
                            VariableStore *globals = [VariableStore sharedInstance];
                            NSDictionary *cookieProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                                                        @"ollie/", NSHTTPCookieDomain,
                                                        @"\\", NSHTTPCookiePath,
                                                        @"Cookie", NSHTTPCookieName,
                                                        globals.sessionInfo, NSHTTPCookieValue,
                                                        nil];
                            NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
                            NSArray *cookieArray = [NSArray arrayWithObject:cookie];
                            NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray];

                            NSMutableString *url = [[NSMutableString alloc] initWithString:@"https://company.com/file.php"];

                            NSURL *urlNew = [NSURL URLWithString:url];
                            self.request = [NSMutableURLRequest requestWithURL:urlNew];
                            [self.request setHTTPMethod:@"GET"];
                            [self.request setAllHTTPHeaderFields:headers];

                            [self waitForData:^(BOOL dataReceived) {
                                if (dataReceived) {
                                    [self waitForESN:^(BOOL esnFound) {
                                        if (esnFound) {
                                            VariableStore *globals = [VariableStore sharedInstance];
                                            getESNForCallback(globals.user_esn, globals.sessionInfo, success, error);
                                        }
                                    }];
                                }
                            }];
                        }
                    }];
                }
            }];
        }
    }];
}

- (void)checkThumb:(touchIDSuccess)compblock {
    LAContext *context = [[LAContext alloc] init];
    NSError *error = nil;

    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        // Authenticate User
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
            localizedReason:@"You need to log in."
                      reply:^(BOOL success, NSError * _Nullable error) {
                          if (success) {
                              NSLog(@"success");
                              compblock(YES);
                          } else {
                              switch (error.code) {
                                  case LAErrorAuthenticationFailed:
                                      break;
                                  case LAErrorUserCancel:
                                      break;
                                  case LAErrorUserFallback:
                                      break;

                                  default:
                                      break;
                              }
                          }
                      }];
    }
}

- (void)readIt:(sessionRetrieved)compblock {
    NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    NSString *url = @"https://company.com/specialstring.php";

    NSMutableString *postText = [[NSMutableString alloc] init];

    [postText appendString:idfv];

    NSString *postBody = [NSString stringWithString:postText];

    XMLPostSecurity *postAction = [[XMLPostSecurity alloc] init];
    VariableStore *globals = [VariableStore sharedInstance];
    globals.sessionInfo = [postAction sendPostRequestToUrl:url withBody:postBody];

    FileSaving *saver = [[FileSaving alloc] init];

    [saver saveSession:globals.sessionInfo];
    compblock(YES);
}

-(void)readNewSession:(sessionReading)compblock {
    NSFileManager *fileManagerTwo;
    NSData *dataBuffer;
    fileManagerTwo = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingString:@"/session.txt"];

    dataBuffer = [fileManagerTwo contentsAtPath:filePath];
    VariableStore *globals = [VariableStore sharedInstance];
    globals.sessionInfo = [[NSString alloc] initWithData:dataBuffer encoding:(NSASCIIStringEncoding)];
    compblock(YES);
}

- (void)checkESN:(checkingESNBlock)callback {
    checkESNWithCallback = callback;
    VariableStore *globals = [VariableStore sharedInstance];
    [self checkTheSession:globals.user_esn withSession:globals.sessionInfo withSuccess:YES error:nil];
}

- (void)checkTheSession:(NSString *)theESN withSession:(NSString *)oldSession withSuccess:(BOOL)success error:(NSError *)error {
    [self readNewSession:^(BOOL seen) {
        if (seen) {
            VariableStore *globals = [VariableStore sharedInstance];
            NSDictionary *cookieProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                                            @"ollie/", NSHTTPCookieDomain,
                                            @"\\", NSHTTPCookiePath,
                                            @"Cookie", NSHTTPCookieName,
                                            globals.sessionInfo, NSHTTPCookieValue,
                                            nil];
            NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
            NSArray *cookieArray = [NSArray arrayWithObject:cookie];
            NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray];

            NSMutableString *url = [[NSMutableString alloc] initWithString:@"https://company.com/file.php"];

            NSURL *urlNew = [NSURL URLWithString:url];
            self.request = [NSMutableURLRequest requestWithURL:urlNew];
            [self.request setHTTPMethod:@"GET"];
            [self.request setAllHTTPHeaderFields:headers];

            [self waitForData:^(BOOL dataReceived) {
                if (dataReceived) {
                    [self waitForESN:^(BOOL esnFound) {
                        if (esnFound) {
                            VariableStore *globals = [VariableStore sharedInstance];
                            checkESNWithCallback(globals.user_esn, globals.sessionInfo, success, error);
                        }
                    }];
                }
            }];
        }
    }];
}

- (void)fillAppointmentData:(fillArray)compblock {

    VariableStore *globals = [VariableStore sharedInstance];

    NSDictionary *cookieProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                                  @"ollie/", NSHTTPCookieDomain,
                                  @"\\", NSHTTPCookiePath,
                                  @"Cookie", NSHTTPCookieName,
                                  globals.sessionInfo, NSHTTPCookieValue,
                                  nil];
    NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
    NSArray *cookieArray = [NSArray arrayWithObject:cookie];
    NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray];

    NSMutableString *url = [[NSMutableString alloc] initWithString:@"https://company.com/file2.php?adb="];

    [url appendString:globals.chosenDate];
    [url appendString:@"&esn="];
    [url appendString:globals.user_esn];

    NSURL *urlNew = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlNew];
    [request setHTTPMethod:@"GET"];
    [request setAllHTTPHeaderFields:headers];

    [self gettingData:^(NSData *myData, NSError *error) {
        if (myData != nil) {
            ParseXML *myParser = [[ParseXML alloc] initWithData:myData];

            [globals.appointmentData removeAllObjects];

            [globals.appointmentData addObjectsFromArray:myParser.items];
        }
    }];
}

- (void) gettingData:(getTheData) compblock {
    VariableStore *globals = [VariableStore sharedInstance];
    globals.got401 = nil;
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:self.request
                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

                                            if (error) {
                                                return;
                                            }

                                            if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                                NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];

                                                if (statusCode != 200) {
                                                    if (statusCode == 401) {
                                                        // Insert process for thumbprint and session cookie pull
                                                        NSFileManager *fileManagerThree = [NSFileManager defaultManager];
                                                        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                                                        NSString *sessionPath = [documentsPath stringByAppendingPathComponent:@"session.txt"];
                                                        NSError *error;
                                                        BOOL success = [fileManagerThree removeItemAtPath:sessionPath error:&error];
                                                        if (success) {
                                                        } else {
                                                        }
                                                        globals.got401 = @"Error";
                                                    } else {
                                                        return;
                                                    }
                                                }
                                            }
                                            self.parseData = data;
                                        }];
    [task resume];
}

@end

1 个答案:

答案 0 :(得分:2)

如果你只有3或4个约会的数据存储在本地,那么答案是“对你来说最简单的”。这没关系。您可以将数据转换为莫尔斯代码并保存点和破折号然后读取它,它仍然会很小且足够快。

您可以将数据保存到plist,使用NSCoding将其序列化,将其保存为SQLite数据库,甚至编写XML并在读取时将其转换回数组(尽管XML选项可能是最慢/最少的)高效。)

核心数据非常强大(非常酷)但它的学习曲线非常陡峭。在你习惯使用iOS之前我不会推荐它。

如果您的应用程序超时,那么可能还有其他错误。编辑您的问题以显示问题区域的代码,也许我们可以提供帮助。