1、JSON解析
- (NSDictionary *)serializedData:(NSData *)data { NSError *JSONSerializationError; NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&JSONSerializationError]; if(JSONSerializationError) { [NSException raise:@"JSON Serialization Error" format:@"Failed to parse weather data"]; } return JSON; }
2、背景模糊,需要UIImage+ImageEffects
- (void)setBlurredOverlayImage { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ { // Take a screen shot of this controller's view UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0.0); CGContextRef context = UIGraphicsGetCurrentContext(); [self.view.layer renderInContext:context]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); // Blur the screen shot UIImage *blurred = [image applyBlurWithRadius:20 tintColor:[UIColor colorWithWhite:0.15 alpha:0.5] saturationDeltaFactor:1.5 maskImage:nil]; dispatch_async(dispatch_get_main_queue(), ^ { // Set the blurred overlay view's image with the blurred screenshot self.blurredOverlayView.image = blurred; }); }); }
3、计算pageControl的页码
- (void)scrollViewDidScroll:(UIScrollView *)scrollView { // Update the current page for the page control float fractionalPage = self.pagingScrollView.contentOffset.x / self.pagingScrollView.frame.size.width; self.pageControl.currentPage = lround(fractionalPage); }
4、图像缩放
+ (UIImage *)scale:(UIImage *)sourceImg toSize:(CGSize)size { UIGraphicsBeginImageContext(size); [sourceImg drawInRect:CGRectMake(0, 0, size.width, size.height)]; UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return scaledImage; } + (CGSize)scaleSize:(CGSize)sourceSize { float width = sourceSize.width; float height = sourceSize.height; if (width >= height) return CGSizeMake(800, 800 * height / width); else return CGSizeMake(800 * width / height, 800); }
5、ASIHTTPRequest取消请求
+ (void)CancelRequest:(ASIHTTPRequest *)request { if (request != nil) { [request cancel]; [request clearDelegatesAndCancel]; } }
6、debug log switch
#ifdef DEBUG # define NSLog(...) NSLog(__VA_ARGS__) #else # define NSLog(...) {} #endif
7、Disk cache
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil]; [NSURLCache setSharedURLCache:URLCache];
8、AFNetworking
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; [[AFNetworkReachabilityManager sharedManager] startMonitoring]; [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { NSString* title = @"网络未连接"; switch (status) { case AFNetworkReachabilityStatusNotReachable: title = @"网络未连接"; break; case AFNetworkReachabilityStatusReachableViaWiFi: title = @"当前wifi已连接"; break; case AFNetworkReachabilityStatusReachableViaWWAN: title = @"当前2g/3g已连接"; break; default: break; } [RCGlobalConfig HUDShowMessage:title addedToView:[UIApplication sharedApplication].keyWindow]; }];
9、MBProgressHUD
+ (MBProgressHUD *)HUDShowMessage:(NSString *)msg addedToView:(UIView *)view { static MBProgressHUD *hud = nil; if (!hud) hud = [MBProgressHUD showHUDAddedTo:view animated:YES]; hud.mode = MBProgressHUDModeText; hud.labelText = msg; hud.hidden = NO; hud.alpha = 1.0f; [hud hide:YES afterDelay:1.0f]; return hud; }
10、UIBarButtonItem
+ (UIBarButtonItem *)createBarButtonItemWithTitle:(NSString *)buttonTitle Target:(id)target action:(SEL)action { UIBarButtonItem *item = nil; item = [[UIBarButtonItem alloc] initWithTitle:buttonTitle style:UIBarButtonItemStylePlain target:target action:action]; return item; } + (UIBarButtonItem *)createMenuBarButtonItemWithTarget:(id)target action:(SEL)action { return [[UIBarButtonItem alloc] initWithImage:[UIImage nimbusImageNamed:@"icon_menu.png"] style:UIBarButtonItemStylePlain target:target action:action]; } + (UIBarButtonItem *)createRefreshBarButtonItemWithTarget:(id)target action:(SEL)action { UIBarButtonItem *item = nil; item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:target action:action]; return item; }
11、获取UIView对应的UIViewController
#import <UIKit/UIKit.h> @interface UIView (findViewController) - (UIViewController *)viewController; @end #import "UIView+findViewController.h" @implementation UIView (findViewController) - (UIViewController *)viewController { // Traverse responder chain. Return first found view controller, which will be the view's view controller. UIResponder *responder = self; while ((responder = [responder nextResponder])) if ([responder isKindOfClass:[UIViewController class]]) return (UIViewController *)responder; // If the view controller isn't found, return nil. return nil; } @end
12、获取图片,需要nimbus
#import <UIKit/UIKit.h> @interface UIImage (nimbusImageNamed) + (UIImage *)nimbusImageNamed:(NSString *)imageName; @end #import "UIImage+nimbusImageNamed.h" @implementation UIImage (nimbusImageNamed) + (UIImage *)nimbusImageNamed:(NSString *)imageName { NSString *imagePath = NIPathForBundleResource(nil, imageName); UIImage *image = [[Nimbus imageMemoryCache] objectWithName:imagePath]; if (nil == image) { image = [UIImage imageWithContentsOfFile:imagePath]; // store it in memory [[Nimbus imageMemoryCache] storeObject:image withName:imagePath]; } return image; } @end
13、保存图片
if(photoView.image) UIImageWriteToSavedPhotosAlbum(photoView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
14、获取文件内容
+ (NSString *)contentForFile:(NSString *)file ofType:(NSString *)type { NSString *filePath=[[NSBundle mainBundle] pathForResource:file ofType:type]; NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; return content; }
15、获取AppDelegate
+ (SFAppDelegate *)applicationDelegate { return (SFAppDelegate *)[[UIApplication sharedApplication] delegate]; }
16、计算字符高度
+ (float)heightOfString:(NSString *)string withWidth:(float)width font:(UIFont *)font { if ([NSNull null] == (id)string) string = @"暂时没有数据"; CGSize constraintSize = CGSizeMake(width, MAXFLOAT); CGSize labelSize = [string sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; return labelSize.height; }
17、设置cookie
NSHTTPCookie *uidCookie = [NSHTTPCookie cookieWithProperties: [NSDictionary dictionaryWithObjectsAndKeys: @"sfuid", NSHTTPCookieName, @"", NSHTTPCookieValue, @".segmentfault.com", NSHTTPCookieDomain, @"segmentfault.com", NSHTTPCookieOriginURL, @"/", NSHTTPCookiePath, @"0", NSHTTPCookieVersion, nil]]; [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:uidCookie];