APPNotificationOptions.m 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. /*
  2. * Apache 2.0 License
  3. *
  4. * Copyright (c) Sebastian Katzer 2017
  5. *
  6. * This file contains Original Code and/or Modifications of Original Code
  7. * as defined in and that are subject to the Apache License
  8. * Version 2.0 (the 'License'). You may not use this file except in
  9. * compliance with the License. Please obtain a copy of the License at
  10. * http://opensource.org/licenses/Apache-2.0/ and read it before using this
  11. * file.
  12. *
  13. * The Original Code and all software distributed under the License are
  14. * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
  15. * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
  16. * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
  18. * Please see the License for the specific language governing rights and
  19. * limitations under the License.
  20. */
  21. #import "APPNotificationOptions.h"
  22. #import "UNUserNotificationCenter+APPLocalNotification.h"
  23. @import CoreLocation;
  24. @import UserNotifications;
  25. @interface APPNotificationOptions ()
  26. // The dictionary which contains all notification properties
  27. @property(nonatomic, retain) NSDictionary* dict;
  28. @end
  29. @implementation APPNotificationOptions : NSObject
  30. @synthesize dict;
  31. #pragma mark -
  32. #pragma mark Initialization
  33. /**
  34. * Initialize by using the given property values.
  35. *
  36. * @param [ NSDictionary* ] dict A key-value property map.
  37. *
  38. * @return [ APPNotificationOptions ]
  39. */
  40. - (id) initWithDict:(NSDictionary*)dictionary
  41. {
  42. self = [self init];
  43. self.dict = dictionary;
  44. [self actions];
  45. return self;
  46. }
  47. #pragma mark -
  48. #pragma mark Properties
  49. /**
  50. * The ID for the notification.
  51. *
  52. * @return [ NSNumber* ]
  53. */
  54. - (NSNumber*) id
  55. {
  56. NSInteger id = [[dict objectForKey:@"id"] integerValue];
  57. return [NSNumber numberWithInteger:id];
  58. }
  59. /**
  60. * The ID for the notification.
  61. *
  62. * @return [ NSString* ]
  63. */
  64. - (NSString*) identifier
  65. {
  66. return [NSString stringWithFormat:@"%@", self.id];
  67. }
  68. /**
  69. * The title for the notification.
  70. *
  71. * @return [ NSString* ]
  72. */
  73. - (NSString*) title
  74. {
  75. return [dict objectForKey:@"title"];
  76. }
  77. /**
  78. * The subtitle for the notification.
  79. *
  80. * @return [ NSString* ]
  81. */
  82. - (NSString*) subtitle
  83. {
  84. NSArray *parts = [self.title componentsSeparatedByString:@"\n"];
  85. return parts.count < 2 ? @"" : [parts objectAtIndex:1];
  86. }
  87. /**
  88. * The text for the notification.
  89. *
  90. * @return [ NSString* ]
  91. */
  92. - (NSString*) text
  93. {
  94. return [dict objectForKey:@"text"];
  95. }
  96. /**
  97. * Show notification.
  98. *
  99. * @return [ BOOL ]
  100. */
  101. - (BOOL) silent
  102. {
  103. return [[dict objectForKey:@"silent"] boolValue];
  104. }
  105. /**
  106. * Show notification in foreground.
  107. *
  108. * @return [ BOOL ]
  109. */
  110. - (int) priority
  111. {
  112. return [[dict objectForKey:@"priority"] intValue];
  113. }
  114. /**
  115. * The badge number for the notification.
  116. *
  117. * @return [ NSNumber* ]
  118. */
  119. - (NSNumber*) badge
  120. {
  121. id value = [dict objectForKey:@"badge"];
  122. return (value == NULL) ? NULL : [NSNumber numberWithInt:[value intValue]];
  123. }
  124. /**
  125. * The category of the notification.
  126. *
  127. * @return [ NSString* ]
  128. */
  129. - (NSString*) categoryId
  130. {
  131. NSString* value = [dict objectForKey:@"actionGroupId"];
  132. return value.length ? value : kAPPGeneralCategory;
  133. }
  134. /**
  135. * The sound file for the notification.
  136. *
  137. * @return [ UNNotificationSound* ]
  138. */
  139. - (UNNotificationSound*) sound
  140. {
  141. NSString* path = [dict objectForKey:@"sound"];
  142. NSString* file;
  143. if ([path isKindOfClass:NSNumber.class]) {
  144. return [path boolValue] ? [UNNotificationSound defaultSound] : NULL;
  145. }
  146. if (!path.length)
  147. return NULL;
  148. if ([path hasPrefix:@"file:/"]) {
  149. file = [self soundNameForAsset:path];
  150. } else
  151. if ([path hasPrefix:@"res:"]) {
  152. file = [self soundNameForResource:path];
  153. }
  154. return [UNNotificationSound soundNamed:file];
  155. }
  156. /**
  157. * Additional content to attach.
  158. *
  159. * @return [ UNNotificationSound* ]
  160. */
  161. - (NSArray<UNNotificationAttachment *> *) attachments
  162. {
  163. NSArray* paths = [dict objectForKey:@"attachments"];
  164. NSMutableArray* attachments = [[NSMutableArray alloc] init];
  165. if (!paths)
  166. return attachments;
  167. for (NSString* path in paths) {
  168. NSURL* url = [self urlForAttachmentPath:path];
  169. UNNotificationAttachment* attachment;
  170. attachment = [UNNotificationAttachment attachmentWithIdentifier:path
  171. URL:url
  172. options:NULL
  173. error:NULL];
  174. if (attachment) {
  175. [attachments addObject:attachment];
  176. }
  177. }
  178. return attachments;
  179. }
  180. /**
  181. * Additional actions for the notification.
  182. *
  183. * @return [ NSArray* ]
  184. */
  185. - (NSArray<UNNotificationAction *> *) actions
  186. {
  187. NSArray* items = [dict objectForKey:@"actions"];
  188. NSMutableArray* actions = [[NSMutableArray alloc] init];
  189. if (!items)
  190. return actions;
  191. for (NSDictionary* item in items) {
  192. NSString* id = [item objectForKey:@"id"];
  193. NSString* title = [item objectForKey:@"title"];
  194. NSString* type = [item objectForKey:@"type"];
  195. UNNotificationActionOptions options = UNNotificationActionOptionNone;
  196. UNNotificationAction* action;
  197. if ([[item objectForKey:@"launch"] boolValue]) {
  198. options = UNNotificationActionOptionForeground;
  199. }
  200. if ([[item objectForKey:@"ui"] isEqualToString:@"decline"]) {
  201. options = options | UNNotificationActionOptionDestructive;
  202. }
  203. if ([[item objectForKey:@"needsAuth"] boolValue]) {
  204. options = options | UNNotificationActionOptionAuthenticationRequired;
  205. }
  206. if ([type isEqualToString:@"input"]) {
  207. NSString* submitTitle = [item objectForKey:@"submitTitle"];
  208. NSString* placeholder = [item objectForKey:@"emptyText"];
  209. if (!submitTitle.length) {
  210. submitTitle = @"Submit";
  211. }
  212. action = [UNTextInputNotificationAction actionWithIdentifier:id
  213. title:title
  214. options:options
  215. textInputButtonTitle:submitTitle
  216. textInputPlaceholder:placeholder];
  217. } else
  218. if (!type.length || [type isEqualToString:@"button"]) {
  219. action = [UNNotificationAction actionWithIdentifier:id
  220. title:title
  221. options:options];
  222. } else {
  223. NSLog(@"Unknown action type: %@", type);
  224. }
  225. if (action) {
  226. [actions addObject:action];
  227. }
  228. }
  229. return actions;
  230. }
  231. #pragma mark -
  232. #pragma mark Public
  233. /**
  234. * Specify how and when to trigger the notification.
  235. *
  236. * @return [ UNNotificationTrigger* ]
  237. */
  238. - (UNNotificationTrigger*) trigger
  239. {
  240. NSString* type = [self valueForTriggerOption:@"type"];
  241. if ([type isEqualToString:@"location"])
  242. return [self triggerWithRegion];
  243. if (![type isEqualToString:@"calendar"])
  244. NSLog(@"Unknown type: %@", type);
  245. if ([self isRepeating])
  246. return [self repeatingTrigger];
  247. return [self nonRepeatingTrigger];
  248. }
  249. /**
  250. * The notification's user info dict.
  251. *
  252. * @return [ NSDictionary* ]
  253. */
  254. - (NSDictionary*) userInfo
  255. {
  256. if ([dict objectForKey:@"updatedAt"]) {
  257. NSMutableDictionary* data = [dict mutableCopy];
  258. [data removeObjectForKey:@"updatedAt"];
  259. return data;
  260. }
  261. return dict;
  262. }
  263. #pragma mark -
  264. #pragma mark Private
  265. - (id) valueForTriggerOption:(NSString*)key
  266. {
  267. return [[dict objectForKey:@"trigger"] objectForKey:key];
  268. }
  269. /**
  270. * The date when to fire the notification.
  271. *
  272. * @return [ NSDate* ]
  273. */
  274. - (NSDate*) triggerDate
  275. {
  276. double timestamp = [[self valueForTriggerOption:@"at"] doubleValue];
  277. return [NSDate dateWithTimeIntervalSince1970:(timestamp / 1000)];
  278. }
  279. /**
  280. * If the notification shall be repeating.
  281. *
  282. * @return [ BOOL ]
  283. */
  284. - (BOOL) isRepeating
  285. {
  286. id every = [self valueForTriggerOption:@"every"];
  287. if ([every isKindOfClass:NSString.class])
  288. return ((NSString*) every).length > 0;
  289. if ([every isKindOfClass:NSDictionary.class])
  290. return ((NSDictionary*) every).count > 0;
  291. return every > 0;
  292. }
  293. /**
  294. * Non repeating trigger.
  295. *
  296. * @return [ UNTimeIntervalNotificationTrigger* ]
  297. */
  298. - (UNNotificationTrigger*) nonRepeatingTrigger
  299. {
  300. id timestamp = [self valueForTriggerOption:@"at"];
  301. if (timestamp) {
  302. return [self triggerWithDateMatchingComponents:NO];
  303. }
  304. return [UNTimeIntervalNotificationTrigger
  305. triggerWithTimeInterval:[self timeInterval] repeats:NO];
  306. }
  307. /**
  308. * Repeating trigger.
  309. *
  310. * @return [ UNNotificationTrigger* ]
  311. */
  312. - (UNNotificationTrigger*) repeatingTrigger
  313. {
  314. id every = [self valueForTriggerOption:@"every"];
  315. if ([every isKindOfClass:NSString.class])
  316. return [self triggerWithDateMatchingComponents:YES];
  317. if ([every isKindOfClass:NSDictionary.class])
  318. return [self triggerWithCustomDateMatchingComponents];
  319. return [self triggerWithTimeInterval];
  320. }
  321. /**
  322. * A trigger based on a calendar time defined by the user.
  323. *
  324. * @return [ UNTimeIntervalNotificationTrigger* ]
  325. */
  326. - (UNTimeIntervalNotificationTrigger*) triggerWithTimeInterval
  327. {
  328. double ticks = [[self valueForTriggerOption:@"every"] doubleValue];
  329. NSString* unit = [self valueForTriggerOption:@"unit"];
  330. double seconds = [self convertTicksToSeconds:ticks unit:unit];
  331. if (seconds < 60) {
  332. NSLog(@"time interval must be at least 60 sec if repeating");
  333. seconds = 60;
  334. }
  335. return [UNTimeIntervalNotificationTrigger
  336. triggerWithTimeInterval:seconds repeats:YES];
  337. }
  338. /**
  339. * A repeating trigger based on a calendar time intervals defined by the plugin.
  340. *
  341. * @return [ UNCalendarNotificationTrigger* ]
  342. */
  343. - (UNCalendarNotificationTrigger*) triggerWithDateMatchingComponents:(BOOL)repeats
  344. {
  345. NSCalendar* cal = [[NSCalendar alloc]
  346. initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
  347. NSDateComponents *date = [cal components:[self repeatInterval]
  348. fromDate:[self triggerDate]];
  349. date.timeZone = [NSTimeZone defaultTimeZone];
  350. return [UNCalendarNotificationTrigger
  351. triggerWithDateMatchingComponents:date repeats:repeats];
  352. }
  353. /**
  354. * A repeating trigger based on a calendar time intervals defined by the user.
  355. *
  356. * @return [ UNCalendarNotificationTrigger* ]
  357. */
  358. - (UNCalendarNotificationTrigger*) triggerWithCustomDateMatchingComponents
  359. {
  360. NSCalendar* cal = [[NSCalendar alloc]
  361. initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
  362. NSDateComponents *date = [self customDateComponents];
  363. date.calendar = cal;
  364. date.timeZone = [NSTimeZone defaultTimeZone];
  365. return [UNCalendarNotificationTrigger
  366. triggerWithDateMatchingComponents:date repeats:YES];
  367. }
  368. /**
  369. * A repeating trigger based on a location region.
  370. *
  371. * @return [ UNLocationNotificationTrigger* ]
  372. */
  373. - (UNLocationNotificationTrigger*) triggerWithRegion
  374. {
  375. NSArray* center = [self valueForTriggerOption:@"center"];
  376. double radius = [[self valueForTriggerOption:@"radius"] doubleValue];
  377. BOOL single = [[self valueForTriggerOption:@"single"] boolValue];
  378. CLLocationCoordinate2D coord =
  379. CLLocationCoordinate2DMake([center[0] doubleValue], [center[1] doubleValue]);
  380. CLCircularRegion* region =
  381. [[CLCircularRegion alloc] initWithCenter:coord
  382. radius:radius
  383. identifier:self.identifier];
  384. region.notifyOnEntry = [[self valueForTriggerOption:@"notifyOnEntry"] boolValue];
  385. region.notifyOnExit = [[self valueForTriggerOption:@"notifyOnExit"] boolValue];
  386. return [UNLocationNotificationTrigger triggerWithRegion:region
  387. repeats:!single];
  388. }
  389. /**
  390. * The time interval between the next fire date and now.
  391. *
  392. * @return [ double ]
  393. */
  394. - (double) timeInterval
  395. {
  396. double ticks = [[self valueForTriggerOption:@"in"] doubleValue];
  397. NSString* unit = [self valueForTriggerOption:@"unit"];
  398. double seconds = [self convertTicksToSeconds:ticks unit:unit];
  399. return MAX(0.01f, seconds);
  400. }
  401. /**
  402. * The repeat interval for the notification.
  403. *
  404. * @return [ NSCalendarUnit ]
  405. */
  406. - (NSCalendarUnit) repeatInterval
  407. {
  408. NSString* interval = [self valueForTriggerOption:@"every"];
  409. NSCalendarUnit units = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
  410. if ([interval isEqualToString:@"minute"])
  411. return NSCalendarUnitSecond;
  412. if ([interval isEqualToString:@"hour"])
  413. return NSCalendarUnitMinute|NSCalendarUnitSecond;
  414. if ([interval isEqualToString:@"day"])
  415. return NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
  416. if ([interval isEqualToString:@"week"])
  417. return NSCalendarUnitWeekday|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
  418. if ([interval isEqualToString:@"month"])
  419. return NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
  420. if ([interval isEqualToString:@"year"])
  421. return NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
  422. return units;
  423. }
  424. /**
  425. * The repeat interval for the notification.
  426. *
  427. * @return [ NSDateComponents* ]
  428. */
  429. - (NSDateComponents*) customDateComponents
  430. {
  431. NSDateComponents* date = [[NSDateComponents alloc] init];
  432. NSDictionary* every = [self valueForTriggerOption:@"every"];
  433. date.second = 0;
  434. for (NSString* key in every) {
  435. long value = [[every valueForKey:key] longValue];
  436. if ([key isEqualToString:@"minute"]) {
  437. date.minute = value;
  438. } else
  439. if ([key isEqualToString:@"hour"]) {
  440. date.hour = value;
  441. } else
  442. if ([key isEqualToString:@"day"]) {
  443. date.day = value;
  444. } else
  445. if ([key isEqualToString:@"weekday"]) {
  446. date.weekday = value;
  447. } else
  448. if ([key isEqualToString:@"weekdayOrdinal"]) {
  449. date.weekdayOrdinal = value;
  450. } else
  451. if ([key isEqualToString:@"week"]) {
  452. date.weekOfYear = value;
  453. } else
  454. if ([key isEqualToString:@"weekOfMonth"]) {
  455. date.weekOfMonth = value;
  456. } else
  457. if ([key isEqualToString:@"month"]) {
  458. date.month = value;
  459. } else
  460. if ([key isEqualToString:@"quarter"]) {
  461. date.quarter = value;
  462. } else
  463. if ([key isEqualToString:@"year"]) {
  464. date.year = value;
  465. }
  466. }
  467. return date;
  468. }
  469. /**
  470. * Convert an assets path to an valid sound name attribute.
  471. *
  472. * @param [ NSString* ] path A relative assets file path.
  473. *
  474. * @return [ NSString* ]
  475. */
  476. - (NSString*) soundNameForAsset:(NSString*)path
  477. {
  478. return [path stringByReplacingOccurrencesOfString:@"file:/"
  479. withString:@"www"];
  480. }
  481. /**
  482. * Convert a ressource path to an valid sound name attribute.
  483. *
  484. * @param [ NSString* ] path A relative ressource file path.
  485. *
  486. * @return [ NSString* ]
  487. */
  488. - (NSString*) soundNameForResource:(NSString*)path
  489. {
  490. return [path pathComponents].lastObject;
  491. }
  492. /**
  493. * URL for the specified attachment path.
  494. *
  495. * @param [ NSString* ] path Absolute/relative path or a base64 data.
  496. *
  497. * @return [ NSURL* ]
  498. */
  499. - (NSURL*) urlForAttachmentPath:(NSString*)path
  500. {
  501. if ([path hasPrefix:@"file:///"])
  502. {
  503. return [self urlForFile:path];
  504. }
  505. else if ([path hasPrefix:@"res:"])
  506. {
  507. return [self urlForResource:path];
  508. }
  509. else if ([path hasPrefix:@"file://"])
  510. {
  511. return [self urlForAsset:path];
  512. }
  513. else if ([path hasPrefix:@"base64:"])
  514. {
  515. return [self urlFromBase64:path];
  516. }
  517. NSFileManager* fm = [NSFileManager defaultManager];
  518. if (![fm fileExistsAtPath:path]){
  519. NSLog(@"File not found: %@", path);
  520. }
  521. return [NSURL fileURLWithPath:path];
  522. }
  523. /**
  524. * URL to an absolute file path.
  525. *
  526. * @param [ NSString* ] path An absolute file path.
  527. *
  528. * @return [ NSURL* ]
  529. */
  530. - (NSURL*) urlForFile:(NSString*)path
  531. {
  532. NSFileManager* fm = [NSFileManager defaultManager];
  533. NSString* absPath;
  534. absPath = [path stringByReplacingOccurrencesOfString:@"file://"
  535. withString:@""];
  536. if (![fm fileExistsAtPath:absPath]) {
  537. NSLog(@"File not found: %@", absPath);
  538. }
  539. return [NSURL fileURLWithPath:absPath];
  540. }
  541. /**
  542. * URL to a resource file.
  543. *
  544. * @param [ NSString* ] path A relative file path.
  545. *
  546. * @return [ NSURL* ]
  547. */
  548. - (NSURL*) urlForResource:(NSString*)path
  549. {
  550. NSFileManager* fm = [NSFileManager defaultManager];
  551. NSBundle* mainBundle = [NSBundle mainBundle];
  552. NSString* bundlePath = [mainBundle resourcePath];
  553. if ([path isEqualToString:@"res://icon"]) {
  554. path = @"res://AppIcon60x60@3x.png";
  555. }
  556. NSString* absPath;
  557. absPath = [path stringByReplacingOccurrencesOfString:@"res:/"
  558. withString:@""];
  559. absPath = [bundlePath stringByAppendingString:absPath];
  560. if (![fm fileExistsAtPath:absPath]) {
  561. NSLog(@"File not found: %@", absPath);
  562. }
  563. return [NSURL fileURLWithPath:absPath];
  564. }
  565. /**
  566. * URL to an asset file.
  567. *
  568. * @param path A relative www file path.
  569. *
  570. * @return [ NSURL* ]
  571. */
  572. - (NSURL*) urlForAsset:(NSString*)path
  573. {
  574. NSFileManager* fm = [NSFileManager defaultManager];
  575. NSBundle* mainBundle = [NSBundle mainBundle];
  576. NSString* bundlePath = [mainBundle bundlePath];
  577. NSString* absPath;
  578. absPath = [path stringByReplacingOccurrencesOfString:@"file:/"
  579. withString:@"/www"];
  580. absPath = [bundlePath stringByAppendingString:absPath];
  581. if (![fm fileExistsAtPath:absPath]) {
  582. NSLog(@"File not found: %@", absPath);
  583. }
  584. return [NSURL fileURLWithPath:absPath];
  585. }
  586. /**
  587. * URL for a base64 encoded string.
  588. *
  589. * @param [ NSString* ] base64String Base64 encoded string.
  590. *
  591. * @return [ NSURL* ]
  592. */
  593. - (NSURL*) urlFromBase64:(NSString*)base64String
  594. {
  595. NSString *filename = [self basenameFromAttachmentPath:base64String];
  596. NSUInteger length = [base64String length];
  597. NSRegularExpression *regex;
  598. NSString *dataString;
  599. regex = [NSRegularExpression regularExpressionWithPattern:@"^base64:[^/]+.."
  600. options:NSRegularExpressionCaseInsensitive
  601. error:Nil];
  602. dataString = [regex stringByReplacingMatchesInString:base64String
  603. options:0
  604. range:NSMakeRange(0, length)
  605. withTemplate:@""];
  606. NSData* data = [[NSData alloc] initWithBase64EncodedString:dataString
  607. options:0];
  608. return [self urlForData:data withFileName:filename];
  609. }
  610. /**
  611. * Extract the attachments basename.
  612. *
  613. * @param [ NSString* ] path The file path or base64 data.
  614. *
  615. * @return [ NSString* ]
  616. */
  617. - (NSString*) basenameFromAttachmentPath:(NSString*)path
  618. {
  619. if ([path hasPrefix:@"base64:"]) {
  620. NSString* pathWithoutPrefix;
  621. pathWithoutPrefix = [path stringByReplacingOccurrencesOfString:@"base64:"
  622. withString:@""];
  623. return [pathWithoutPrefix substringToIndex:
  624. [pathWithoutPrefix rangeOfString:@"//"].location];
  625. }
  626. return path;
  627. }
  628. /**
  629. * Write the data into a temp file.
  630. *
  631. * @param [ NSData* ] data The data to save to file.
  632. * @param [ NSString* ] name The name of the file.
  633. *
  634. * @return [ NSURL* ]
  635. */
  636. - (NSURL*) urlForData:(NSData*)data withFileName:(NSString*) filename
  637. {
  638. NSFileManager* fm = [NSFileManager defaultManager];
  639. NSString* tempDir = NSTemporaryDirectory();
  640. [fm createDirectoryAtPath:tempDir withIntermediateDirectories:YES
  641. attributes:NULL
  642. error:NULL];
  643. NSString* absPath = [tempDir stringByAppendingPathComponent:filename];
  644. NSURL* url = [NSURL fileURLWithPath:absPath];
  645. [data writeToURL:url atomically:NO];
  646. if (![fm fileExistsAtPath:absPath]) {
  647. NSLog(@"File not found: %@", absPath);
  648. }
  649. return url;
  650. }
  651. /**
  652. * Convert the amount of ticks into seconds.
  653. *
  654. * @param [ double ] ticks The amount of ticks.
  655. * @param [ NSString* ] unit The unit of the ticks (minute, hour, day, ...)
  656. *
  657. * @return [ double ] Amount of ticks in seconds.
  658. */
  659. - (double) convertTicksToSeconds:(double)ticks unit:(NSString*)unit
  660. {
  661. if ([unit isEqualToString:@"second"]) {
  662. return ticks;
  663. } else
  664. if ([unit isEqualToString:@"minute"]) {
  665. return ticks * 60;
  666. } else
  667. if ([unit isEqualToString:@"hour"]) {
  668. return ticks * 60 * 60;
  669. } else
  670. if ([unit isEqualToString:@"day"]) {
  671. return ticks * 60 * 60 * 24;
  672. } else
  673. if ([unit isEqualToString:@"week"]) {
  674. return ticks * 60 * 60 * 24 * 7;
  675. } else
  676. if ([unit isEqualToString:@"month"]) {
  677. return ticks * 60 * 60 * 24 * 30.438;
  678. } else
  679. if ([unit isEqualToString:@"quarter"]) {
  680. return ticks * 60 * 60 * 24 * 91.313;
  681. } else
  682. if ([unit isEqualToString:@"year"]) {
  683. return ticks * 60 * 60 * 24 * 365;
  684. }
  685. return 0;
  686. }
  687. @end