-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEMiOS+Convenience.m
540 lines (426 loc) · 14.7 KB
/
EMiOS+Convenience.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
// EMiOS+Convenience.m
// Created by erwin on 12/3/12.
/*
Copyright (c) 2012 eMaza Mobile. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#import "EMiOS+Convenience.h"
#pragma mark NSObject
@implementation NSObject (EMiOS_Convenience)
- (void*)performSelector:(SEL)selector withValue:(void*)value afterDelay:(NSTimeInterval*)delay {
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:self];
[invocation setArgument:value atIndex:2];
[invocation invoke];
NSUInteger length = [[invocation methodSignature] methodReturnLength];
// If method is non-void:
if (length > 0) {
void *buffer = (void*)malloc(length);
[invocation getReturnValue:buffer];
return buffer;
}
// If method is void:
return NULL;
}
@end
#pragma mark NSNumber
@implementation NSNumber (EMiOS_Convenience)
- (NSNumber*)add:(int)value {
return [NSNumber numberWithInt:[self intValue] + value];
}
@end
#pragma mark NSString
@implementation NSString (EMiOS_Convenience)
- (NSString*)fullyEncodedStringWithEncoding:(NSStringEncoding)encoding {
return (__bridge_transfer NSString*)CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)self, NULL, (CFStringRef)@";/?:@&=$+{}<>,[] #%'*!", CFStringConvertNSStringEncodingToEncoding(encoding));
}
- (NSString*)fullyEncodedString {
return [self fullyEncodedStringWithEncoding:kCFStringEncodingUTF8];
}
- (UIColor*)toColor {
// The string should be something like "UIDeviceRGBColorSpace 0.5 0 0.25 1
UIColor *color = [UIColor blackColor];
@try {
NSArray *values = [NSArray arrayWithArray:[self componentsSeparatedByString:@" "]];
CGFloat red = [[values objectAtIndex:1] floatValue];
CGFloat green = [[values objectAtIndex:2] floatValue];
CGFloat blue = [[values objectAtIndex:3] floatValue];
CGFloat alpha = [[values objectAtIndex:4] floatValue];
color = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
values = nil;
}
@catch (NSException * e) {
NSLog(@"Failed to convert '%@' to a color", self);
}
return color;
}
- (NSDate*)toDate {
NSDate *date = [NSDate date];
@try {
int interval = [self intValue];
date = [NSDate dateWithTimeIntervalSince1970:interval];
}
@catch (NSException * e) {
NSLog(@"Failed to convert '%@' to a date", self);
}
return date;
}
- (NSString*)stringBySanitizingUserContent {
return [[self stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""] stringByReplacingOccurrencesOfString:@"\n" withString:@"\\\n"];
}
- (NSString*)possessiveVariant {
if ([self hasSuffix:@"'s"]) return self;
if ([self hasSuffix:@"s'"]) return self;
if ([self hasSuffix:@"s"]) return [NSString stringWithFormat:@"%@'", self];
return [NSString stringWithFormat:@"%@'s", self];
}
@end
#pragma mark DateFormatting
@implementation NSDate (EMiOS_Convenience)
- (NSString*)toUserFormat {
NSString *formattedDate = @"";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.doesRelativeDateFormatting = TRUE;
[formatter setDateFormat:kUserDateFormat];
formattedDate = [formatter stringFromDate:self];
return formattedDate;
}
- (NSString*)toUserShortFormat {
NSString *formattedDate = @"";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:kUserDateShortFormat];
formattedDate = [formatter stringFromDate:self];
return formattedDate;
}
- (NSString*)toServerFormat {
NSString *formattedDate = @"";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"]; // kISO8061DateFormat (aws sdk)
formattedDate = [formatter stringFromDate:self];
return formattedDate;
}
@end
#pragma mark NSDictionary
@implementation NSDictionary (EMiOS_Convenience)
- (NSString*)stringForKey:(NSString*)key {
NSString *string = @"";
@try {
if ([[self valueForKey:key] isEqual:[NSNull null]]) {
NSLog(@"ERROR: null value for key: %@", key);
return string;
}
if ([self valueForKey:key]) {
string = (NSString*)[self valueForKey:key];
}
}
@catch (NSException *exception) {
NSLog(@"ERROR: could not get string for key: %@", key);
}
return string;
}
- (NSNumber*)numberForKey:(NSString*)key {
NSNumber *number = NULL;
@try {
if ([self valueForKey:key]) {
number = (NSNumber*)[self valueForKey:key];
}
}
@catch (NSException *exception) {
NSLog(@"ERROR: could not get number for key: %@", key);
}
return number;
}
- (NSDate*)dateForDateKey:(NSString*)key {
NSDate *date = [NSDate date];
@try {
NSString *string = @"";
if ([self valueForKey:key]) {
string = (NSString*)[self valueForKey:key];
date = [string toDate];
}
}
@catch (NSException *exception) {
NSLog(@"ERROR: could not get date for key: %@", key);
}
return date;
}
- (int)intForKey:(NSString*)key {
int value = 0;
@try {
if ([self valueForKey:key]) {
value = [[self valueForKey:key] intValue];
}
}
@catch (NSException *exception) {
NSLog(@"ERROR: could not get integer for key: %@", key);
}
return value;
}
- (BOOL)boolForKey:(NSString*)key {
BOOL value = FALSE;
@try {
if ([self valueForKey:key]) {
value = [[self valueForKey:key] boolValue];
}
}
@catch (NSException *exception) {
NSLog(@"ERROR: could not get BOOL for key: %@", key);
}
return value;
}
@end
#pragma mark NSSet
@implementation NSSet (EMiOS_Convenience)
@end
#pragma mark NSOrderedSet
@implementation NSOrderedSet (EMiOS_Convenience)
- (NSUInteger)loopedIndexForProposedIndex:(NSUInteger)index {
if (index < [self count]) return index;
double intpart;
modf((CGFloat)index / (CGFloat)[self count], &intpart);
index -= [self count] * intpart;
return index;
}
@end
#pragma mark Array
@implementation NSArray (EMiOS_Convenience)
- (id)loopedObjectAtProposedIndex:(NSUInteger)index {
if (index < [self count]) return [self objectAtIndex:index];
return [self objectAtIndex:[self loopedIndexForProposedIndex:index]];
}
- (NSUInteger)loopedIndexForProposedIndex:(NSUInteger)index {
if (index < [self count]) return index;
double intpart;
modf((CGFloat)index / (CGFloat)[self count], &intpart);
index -= [self count] * intpart;
return index;
}
- (id)randomObject {
NSUInteger count = [self count];
if (count == 0) return nil;
NSUInteger n = arc4random_uniform((uint)count);
return [self objectAtIndex:n];
}
@end
#pragma mark Array Shuffling
@implementation NSMutableArray (EMiOS_Convenience)
- (void)shuffle {
NSUInteger count = [self count];
if (count == 0) return;
for (NSUInteger i = count - 1; i > 0; i--) {
NSUInteger n = arc4random_uniform((uint)i + 1);
[self exchangeObjectAtIndex:i withObjectAtIndex:n];
}
}
@end
#pragma mark UIImage
@implementation UIImage (EMiOS_Convenience)
- (UIImage*)antiAliased {
CGRect imageRect = CGRectMake(0, 0, self.size.width, self.size.height);
UIGraphicsBeginImageContextWithOptions(imageRect.size, TRUE, 0.0);
[self drawInRect:CGRectMake(1, 1, self.size.width - 2, self.size.height - 2)];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
@end
#pragma mark UIView
@implementation UIView (EMiOS_Convenience)
- (void)centerInContainer {
CGRect selfFrame = self.frame;
CGRect superFrame = self.superview.frame;
selfFrame.origin.y = (CGFloat)floor((superFrame.size.height - selfFrame.size.height) / 2);
selfFrame.origin.x = (CGFloat)floor((superFrame.size.width - selfFrame.size.width) / 2);
self.frame = selfFrame;
}
- (void)centerVerticallyInContainer {
CGRect selfFrame = self.frame;
CGRect superFrame = self.superview.frame;
selfFrame.origin.y = (CGFloat)floor((superFrame.size.height - selfFrame.size.height) / 2);
self.frame = selfFrame;
}
- (void)centerHorizontallyInContainer {
CGRect selfFrame = self.frame;
CGRect superFrame = self.superview.frame;
selfFrame.origin.x = (CGFloat)floor((superFrame.size.width - selfFrame.size.width) / 2);
self.frame = selfFrame;
}
- (void)addShadow {
self.clipsToBounds = FALSE;
self.layer.shadowColor = [[UIColor lightGrayColor] CGColor];
self.layer.shadowOffset = CGSizeMake(3, 2);
self.layer.shadowOpacity = 0.85f;
self.layer.shadowRadius = 2;
}
- (void)roundCorners {
self.clipsToBounds = TRUE;
self.layer.cornerRadius = 5;
}
- (void)removeSubviews {
for (UIView *view in self.subviews) {
[view removeFromSuperview];
}
}
- (void)removeSubviewsOfClass:(Class)class {
for (UIView *view in self.subviews) {
if ([view isMemberOfClass:class]) [view removeFromSuperview];
}
}
- (void)setFrameAttribute:(enumFrameAttribute)attribute value:(int)value {
CGRect myFrame = self.frame;
switch (attribute) {
case frameAttributeX: {
myFrame.origin.x = value;
break;
} case frameAttributeY: {
myFrame.origin.y = value;
break;
} case frameAttributeWidth: {
myFrame.size.width = value;
break;
} case frameAttributeHeight: {
myFrame.size.height = value;
break;
}
}
self.frame = myFrame;
}
- (NSValue*)absoluteCoordsInTopLevelView:(UIView*)topView {
CGPoint center = [topView convertPoint:self.center fromView:self.superview];
return [NSValue valueWithCGPoint:center];
}
- (UIImage*)snapshot {
LogMethod
UIGraphicsBeginImageContextWithOptions(self.frame.size, FALSE, 0.0f);
if (CATransform3DIsIdentity(self.layer.transform)) {
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
} else {
[self.layer.superlayer renderInContext:UIGraphicsGetCurrentContext()];
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- (UIImage*)snapshotOfViewHierarchy {
LogMethod
UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, UIScreen.mainScreen.scale);
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:TRUE];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- (UIImage*)snapshotOfWindow {
LogMethod
UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, YES, UIScreen.mainScreen.scale);
[self.window drawViewHierarchyInRect:self.window.bounds afterScreenUpdates:FALSE];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// UIInterfaceOrientation interfaceOrientation = UIInterfaceOrientationLandscapeLeft;
// if (interfaceOrientation != UIInterfaceOrientationPortrait) {
//
// CGSize size = self.window.bounds.size;
// CGSize newSize = CGSizeMake(size.height, size.width);
//
// UIImageOrientation newOrientation = UIImageOrientationDown;
// if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft) newOrientation = UIImageOrientationRight;
// if (interfaceOrientation == UIInterfaceOrientationLandscapeRight) newOrientation = UIImageOrientationLeft;
//
// UIImage *image2 = [[UIImage alloc] initWithCGImage:image.CGImage scale:UIScreen.mainScreen.scale orientation:newOrientation];
//
// UIGraphicsBeginImageContextWithOptions(newSize, YES, UIScreen.mainScreen.scale);
// [image2 drawAtPoint:CGPointZero];
// image = UIGraphicsGetImageFromCurrentImageContext();
// UIGraphicsEndImageContext();
// }
return image;
}
@end
#pragma mark UIViewController
@implementation UIViewController (EMiOS_Convenience)
- (void)forcePopoverSize {
if ([self respondsToSelector:NSSelectorFromString(@"setPreferredContentSize:")]) {
CGSize currentSetSizeForPopover = [[self valueForKey:@"preferredContentSize"] CGSizeValue];
CGSize tmpSize = CGSizeMake(currentSetSizeForPopover.width - 1.0f, currentSetSizeForPopover.height - 1.0f);
[self setValue:[NSValue valueWithCGSize:tmpSize] forKey:@"preferredContentSize"];
[self setValue:[NSValue valueWithCGSize:currentSetSizeForPopover] forKey:@"preferredContentSize"];
} else {
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
CGSize currentSetSizeForPopover = self.contentSizeForViewInPopover;
CGSize tmpSize = CGSizeMake(currentSetSizeForPopover.width - 1.0f, currentSetSizeForPopover.height - 1.0f);
self.contentSizeForViewInPopover = tmpSize;
self.contentSizeForViewInPopover = currentSetSizeForPopover;
#pragma clang diagnostic warning "-Wdeprecated-declarations"
}
}
@end
#pragma mark UITextField
@implementation UITextField (EMiOS_Convenience)
- (NSString*)sanitized {
NSString *sanitized = [self.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
sanitized = [sanitized stringByReplacingOccurrencesOfString:@"'" withString:@""];
return sanitized;
}
@end
#pragma mark UIColor
@implementation UIColor (EMiOS_Convenience)
- (NSString*)toString {
return [NSString stringWithFormat:@"%@", self];
}
@end
@implementation UICollectionView (EMiOS_Convenience)
- (void)nudgeScrollVertical:(BOOL)vertical {
CGPoint currentOfffset = self.contentOffset;
if (vertical) {
[self setContentOffset:CGPointMake(0, currentOfffset.y+1) animated:FALSE];
[self setContentOffset:CGPointMake(0, currentOfffset.y) animated:TRUE];
} else {
[self setContentOffset:CGPointMake(currentOfffset.x+1, 0) animated:FALSE];
[self setContentOffset:CGPointMake(currentOfffset.x, 0) animated:TRUE];
}
}
@end
#pragma mark More Device Info
#include <sys/types.h>
#include <sys/sysctl.h>
@implementation UIDevice (EMiOS_Convenience)
- (NSString*)platform {
int mib[2];
size_t len;
char *machine;
mib[0] = CTL_HW;
mib[1] = HW_MACHINE;
sysctl(mib, 2, NULL, &len, NULL, 0);
machine = malloc(len);
sysctl(mib, 2, machine, &len, NULL, 0);
NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
free(machine);
return platform;
}
@end
#pragma mark UserDefaults
@implementation NSUserDefaults (EMiOS_Convenience)
- (NSString*)stringForKey:(NSString*)key default:(NSString*)defaultValue {
NSString *value = [self stringForKey:key];
return ([value length] > 0)? value : defaultValue;
}
- (NSInteger)enumForKey:(NSString*)key default:(NSInteger)defaultValue {
NSInteger value = [self integerForKey:key];
return (value > 0)? value : defaultValue;
}
@end