FIRKeyedArchivingUtils.m 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FirebaseInstallations/Source/Tests/Utils/FIRKeyedArchivingUtils.h"
  17. @implementation FIRKeyedArchivingUtils
  18. + (nullable NSData *)archivedDataWithRootObject:(id)object error:(NSError **)outError {
  19. NSData *archivedData;
  20. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, *)) {
  21. archivedData = [NSKeyedArchiver archivedDataWithRootObject:object
  22. requiringSecureCoding:YES
  23. error:outError];
  24. } else {
  25. @try {
  26. NSMutableData *data = [NSMutableData data];
  27. NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
  28. archiver.requiresSecureCoding = YES;
  29. [archiver encodeObject:object forKey:NSKeyedArchiveRootObjectKey];
  30. [archiver finishEncoding];
  31. archivedData = [data copy];
  32. } @catch (NSException *exception) {
  33. if (outError) {
  34. NSString *failureReason = [NSString stringWithFormat:@"Exception: %@", exception];
  35. *outError = [NSError errorWithDomain:@"FIRKeyedArchivingUtils"
  36. code:-1
  37. userInfo:@{
  38. NSLocalizedFailureReasonErrorKey : failureReason,
  39. }];
  40. }
  41. }
  42. }
  43. return archivedData;
  44. }
  45. + (nullable id)unarchivedObjectOfClass:(Class)class
  46. fromData:(NSData *)data
  47. error:(NSError **)outError {
  48. id object;
  49. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, *)) {
  50. object = [NSKeyedUnarchiver unarchivedObjectOfClass:class fromData:data error:outError];
  51. } else {
  52. @try {
  53. NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
  54. unarchiver.requiresSecureCoding = YES;
  55. object = [unarchiver decodeObjectOfClass:class forKey:NSKeyedArchiveRootObjectKey];
  56. } @catch (NSException *exception) {
  57. if (outError) {
  58. NSString *failureReason = [NSString stringWithFormat:@"Exception: %@", exception];
  59. *outError = [NSError errorWithDomain:@"FIRKeyedArchivingUtils"
  60. code:-1
  61. userInfo:@{
  62. NSLocalizedFailureReasonErrorKey : failureReason,
  63. }];
  64. }
  65. }
  66. }
  67. return object;
  68. }
  69. @end