FRCLog.m 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2019 Google
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import "FRCLog.h"
  15. #import <UIKit/UIKit.h>
  16. @implementation FRCLog
  17. __weak UITextView* _logView;
  18. NSString* _textUntilTextViewSet;
  19. + (instancetype)sharedInstance {
  20. static dispatch_once_t onceToken;
  21. static FRCLog* sharedInstance;
  22. dispatch_once(&onceToken, ^{
  23. sharedInstance = [[FRCLog alloc] init];
  24. });
  25. return sharedInstance;
  26. }
  27. - (void)setLogView:(UITextView*)view {
  28. _logView = view;
  29. _logView.text = @"";
  30. }
  31. - (void)logToConsoleInternal:(NSString*)text {
  32. NSDate* now = [NSDate date];
  33. NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
  34. [dateFormatter setDateFormat:@"HH:mm:ss"];
  35. NSString* append =
  36. [[NSString stringWithFormat:@"FRCLog(%@): ", [dateFormatter stringFromDate:now]]
  37. stringByAppendingString:text];
  38. append = [append stringByAppendingString:@"\n"];
  39. NSLog(@"%@", append);
  40. if (!_logView) {
  41. NSLog(@"FRCLog: Logview not set");
  42. if (!_textUntilTextViewSet) _textUntilTextViewSet = [[NSString alloc] initWithString:append];
  43. [_textUntilTextViewSet stringByAppendingString:append];
  44. } else {
  45. if (_textUntilTextViewSet) {
  46. _logView.text = _textUntilTextViewSet;
  47. _textUntilTextViewSet = nil;
  48. }
  49. _logView.text = [_logView.text stringByAppendingString:append];
  50. }
  51. [self scrollToBottom];
  52. }
  53. - (void)logToConsole:(NSString*)text {
  54. if ([NSThread isMainThread]) {
  55. [self logToConsoleInternal:text];
  56. } else {
  57. dispatch_async(dispatch_get_main_queue(), ^{
  58. [self logToConsoleInternal:text];
  59. });
  60. }
  61. }
  62. - (void)scrollToBottom {
  63. if (_logView && _logView.text.length > 0) {
  64. [_logView scrollRangeToVisible:NSMakeRange(_logView.text.length - 1, 1)];
  65. }
  66. }
  67. @end