QNUserAgent.m 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. //
  2. // QNUserAgent.m
  3. // QiniuSDK
  4. //
  5. // Created by bailong on 14-9-29.
  6. // Copyright (c) 2014年 Qiniu. All rights reserved.
  7. //
  8. #import <Foundation/Foundation.h>
  9. #if __IPHONE_OS_VERSION_MIN_REQUIRED
  10. #import <MobileCoreServices/MobileCoreServices.h>
  11. #import <UIKit/UIKit.h>
  12. #else
  13. #import <CoreServices/CoreServices.h>
  14. #endif
  15. #import "QNUserAgent.h"
  16. #import "QNVersion.h"
  17. static NSString *qn_clientId(void) {
  18. #if __IPHONE_OS_VERSION_MIN_REQUIRED
  19. NSString *s = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
  20. if (s == nil) {
  21. s = @"simulator";
  22. }
  23. return s;
  24. #else
  25. long long now_timestamp = [[NSDate date] timeIntervalSince1970] * 1000;
  26. int r = arc4random() % 1000;
  27. return [NSString stringWithFormat:@"%lld%u", now_timestamp, r];
  28. #endif
  29. }
  30. static NSString *qn_userAgent(NSString *id, NSString *ak) {
  31. #if __IPHONE_OS_VERSION_MIN_REQUIRED
  32. return [NSString stringWithFormat:@"QiniuObject-C/%@ (%@; iOS %@; %@; %@)", kQiniuVersion, [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], id, ak];
  33. #else
  34. return [NSString stringWithFormat:@"QiniuObject-C/%@ (Mac OS X %@; %@; %@)", kQiniuVersion, [[NSProcessInfo processInfo] operatingSystemVersionString], id, ak];
  35. #endif
  36. }
  37. @interface QNUserAgent ()
  38. @property (nonatomic) NSString *ua;
  39. @end
  40. @implementation QNUserAgent
  41. - (NSString *)description {
  42. return _ua;
  43. }
  44. - (instancetype)init {
  45. if (self = [super init]) {
  46. _id = qn_clientId();
  47. }
  48. return self;
  49. }
  50. /**
  51. * UserAgent
  52. */
  53. - (NSString *)getUserAgent:(NSString *)access {
  54. NSString *ak;
  55. if (access == nil || access.length == 0) {
  56. ak = @"-";
  57. } else {
  58. ak = access;
  59. }
  60. return qn_userAgent(_id, ak);
  61. }
  62. /**
  63. * 单例
  64. */
  65. + (instancetype)sharedInstance {
  66. static QNUserAgent *sharedInstance = nil;
  67. static dispatch_once_t onceToken;
  68. dispatch_once(&onceToken, ^{
  69. sharedInstance = [[self alloc] init];
  70. });
  71. return sharedInstance;
  72. }
  73. @end