0
点赞
收藏
分享

微信扫一扫

iOS开发常用的第三方类库


IOS常用类库



目录[-]



  • Reachability 检测网络连接
  • ASIHTTPRequest 网络请求
  • MBProgressHUD 提示效果
  • SVProgressHUD 提示效果
  • ZAActivityBar 提示效果
  • SBJson JSON解析
  • JSONKit JSON解析
  • SDWebImage 图片异步加载及缓存
  • UIActivityIndicator-for-SDWebImage 为SDWebImage显示加载效果
  • UIImage+Resize 调整图片大小
  • ImageCacheResize 异步加载图片、缓存及调整大小
  • PullToRefresh 下拉刷新
  • SVPullToRefresh 下拉刷新、上拉加载更多
  • CMPopTipView 提示信息
  • PrettyKit
  • MGBox2
  • Nimbus
  • FlatUIKit
  • MUKMediaGallery
  • MWPhotoBrowser
  • ios-image-filters
  • PDF Reader Core for iOS
  • DTCoreText
  • FTCoreText
  • CoreTextWrapper
  • Base64
  • RNCryptor



在iOS开发中不可避免的会用到一些第三方类库,它们提供了很多实用的功能,使我们的开发变得更有效率;同时,也可以从它们的源代码中学习到很多有用的东西。



Reachability 检测网络连接

用来检查网络连接是否可用:包括WIFI和WWAN(3G/EDGE/CDMA等)两种工作模式。

可以从Apple网站下载到:http://developer.apple.com/library/ios/#samplecode/Reachability/History/History.html#//apple_ref/doc/uid/DTS40007324-RevisionHistory-DontLinkElementID_1 

现在有更好的替代品:https://github.com/tonymillion/Reachability,比Apple提供的兼容性更好,而且更加好用,更具体的使用方法请看它提供的例子。


Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];


reach.reachableBlock = ^(Reachability*reach) {


   NSLog(@"网络可用!");


};


reach.unreachableBlock = ^(Reachability*reach) {


   NSLog(@"网络不可用!");


};


// 开始监听


[reach startNotifier];




ASIHTTPRequest 网络请求

ASIHTTPRequest是对CFNetwork API的一个包装,它提供了一套更加简洁的API,使用起来也更加简单。

官方网站:http://allseeing-i.com/ASIHTTPRequest/

GitHub:https://github.com/pokeb/asi-http-request

它不仅仅支持基本的HTTP请求,而且支持基于REST的服务(GET/POST/PUT/DELETE)。

最让人喜欢的是,它支持block语法:


NSURL *url = [NSURL URLWithString:@"            http://allseeing-i.com            "];


__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];


[request setCompletionBlock:^{


  // Use when fetching text data


  NSString *responseString = [request responseString];





  // Use when fetching binary data


  NSData *responseData = [request responseData];


}];


[request setFailedBlock:^{


  NSError *error = [request error];


}];


[request startAsynchronous];



它的ASIFormDataRequest子类可以横容易的提交表单数据和文件:


ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];


[request setPostValue:@"Ben" forKey:@"first_name"];


[request setPostValue:@"Copsey" forKey:@"last_name"];


// Upload a file on disk


[request setFile:@"/Users/ben/Desktop/ben.jpg" withFileName:@"myphoto.jpg" andContentType:@"image/jpeg"


forKey:@"photo"];


// Upload an NSData instance


[request setData:imageData withFileName:@"myphoto.jpg" andContentType:@"image/jpeg" forKey:@"photo"];



详细的使用方法请下载相应的源代码及例子,或者从官方的使用说明http://allseeing-i.com/ASIHTTPRequest/How-to-use开始。



MBProgressHUD 提示效果

支持各种状态加载的提示效果,以及带进度的提示效果。

GitHub:https://github.com/matej/MBProgressHUD

一般会在.m文件实现MBProgressHUDDelegate协议,并声明HUD变量:



 @interface SampleViewController ()


{


   MBProgressHUD *HUD;


}


#pragma mark -


#pragma mark MBProgressHUDDelegate methods





- (void)hudWasHidden:(MBProgressHUD *)hud {


 // Remove HUD from screen when the HUD was hidded


 [HUD removeFromSuperview];


 HUD = nil;


}



在执行某个异步请求时开始调用:


HUD = [MBProgressHUD showHUDAddedTo:self.webView animated:YES];


HUD.labelText = @"正在请求...";


// mode参数可以控制显示的模式


//HUD.mode = MBProgressHUDModeText;


HUD.delegate = self;



请求完成时隐藏提示效果:

[HUD hide:YES];



对于同步方法一般都是用showWhileExecuting方法,方法执行完成之后会自动隐藏提示效果:



[HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];




SVProgressHUD 提示效果

GitHub:https://github.com/samvermette/SVProgressHUD

SVProgressHUD和MBProgressHUD效果差不多,不过不需要使用协议,同时也不需要声明实例。

直接通过类方法进行调用即可:


[SVProgressHUD method]


可以使用以下方法来显示状态:


+ (void)show;


+ (void)showWithMaskType:(SVProgressHUDMaskType)maskType;


+ (void)showWithStatus:(NSString*)string;


+ (void)showWithStatus:(NSString*)string maskType:(SVProgressHUDMaskType)maskType;



如果需要明确的进度,则使用以下方法:


+ (void)showProgress:(CGFloat)progress;


+ (void)showProgress:(CGFloat)progress status:(NSString*)status;


+ (void)showProgress:(CGFloat)progress status:(NSString*)status maskType:(SVProgressHUDMaskType)maskType;



通过dismiss方法来隐藏提示:


+ (void)dismiss;



另外提供了以下方法用于显示状态,并在1秒后自动隐藏提示(使用的图标来源于Glyphish:http://www.glyphish.com/):


+ (void)showSuccessWithStatus:(NSString*)string;


+ (void)showErrorWithStatus:(NSString *)string;


+ (void)showImage:(UIImage*)image status:(NSString*)string;// use 28x28 white pngs




ZAActivityBar 提示效果

GitHub:https://github.com/zacaltman/ZAActivityBar

ZAActivityBar和SVProgressHUD非常相似,它提供了更加简洁的API来显示提示效果。

ZAActivityBar使用的动画效果来源于ZKBounceAnimation(https://github.com/khanlou/SKBounceAnimation),成功、失败的状态图标来源于Pictos(http://pictos.cc/)。

显示加载状态:

[ZAActivityBar showWithStatus:@"加载中..."];


显示成功、失败状态:


[ZAActivityBar showSuccessWithStatus:@"成功!"];


[ZAActivityBar showErrorWithStatus:@"失败!"];



隐藏提示:


[ZAActivityBar dismiss];




SBJson JSON解析

官方: http://sbjson.org/

GitHub:https://github.com/stig/json-framework

API使用起来稍显繁琐,特别是初始化的时候:

 @interface TestViewController () {


   SBJsonStreamParser *parser;


   SBJsonStreamParserAdapter *adapter;


}





// 冗长的初始化方法足以吓到一大片人


- (void)initSBJSON


{


   // We don't want *all* the individual messages from the


 // SBJsonStreamParser, just the top-level objects. The stream


 // parser adapter exists for this purpose.


 adapter = [[SBJsonStreamParserAdapter alloc] init];


  


 // Set ourselves as the delegate, so we receive the messages


 // from the adapter.


 adapter.delegate = self;


  


 // Create a new stream parser..


 parser = [[SBJsonStreamParser alloc] init];


  


 // .. and set our adapter as its delegate.


 parser.delegate = adapter;


  


 // Normally it's an error if JSON is followed by anything but


 // whitespace. Setting this means that the parser will be


 // expecting the stream to contain multiple whitespace-separated


 // JSON documents.


 parser.supportMultipleDocuments


}





#pragma mark SBJsonStreamParserAdapterDelegate methods





- (void)parser:(SBJsonStreamParser *)parser foundArray:(NSArray *)array {


   [NSExceptionraise:@"unexpected" format:@"Should not get here"];


}





- (void)parser:(SBJsonStreamParser *)parser foundObject:(NSDictionary *)dict {


   NSLog(@"SBJson parser foundObject");


   // 处理返回的数据


}





// 使用ASIHTTPRequest请求测试


- (void) loadData {


   __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];


   [request setRequestMethod:@"POST"];


   [request setCompletionBlock:^{


       // Use when fetching text data


       //NSString *responseString = [request responseString];


       // Use when fetching binary data


       NSData *responseData = [request responseData];


       NSLog(@"Connection didReceiveData of length: %u", responseData.length);


        


       // Parse the new chunk of data. The parser will append it to


       // its internal buffer, then parse from where it left off in


       // the last chunk.


       SBJsonStreamParserStatus


        


       if (status == SBJsonStreamParserError) {


           NSLog(@"Parser error: %@", parser.error);


       }else if (status == SBJsonStreamParserWaitingForData) {


           NSLog(@"Parser waiting for more data");


       }


   }];


   [request setFailedBlock:^{


       NSError *error = [request error];


       NSLog(@"failed - %@ %@", [error localizedDescription], error);


   }];


   [request startAsynchronous];


}




JSONKit JSON解析

GitHub:https://github.com/johnezang/JSONKit

提供比SBJson更优异的性能以及更加简便的使用方法,但是中文最好使用utf-8格式(\uXXXX),否则容易造成乱码。

API调用起来非常简单,省去了SBJson那么一大堆的方法:


JSONDecoder* decoder = [[JSONDecoder alloc] initWithParseOptions:JKParseOptionNone];


id result = [decoder objectWithData:jsonData];



详细的使用方法请看它的GitHub主页。



SDWebImage 图片异步加载及缓存

SDWebImage用于异步下载网络上的图片,并支持对图片的缓存等。

多数情况下是使用UIImageView+WebCache为UIImageView异步加载图片:


#import


// ...


[cell.imageView setImageWithURL:[NSURL URLWithString:@"            http://www.domain.com/path/to/image.jpg            "]


                  placeholderImage:[UIImage imageNamed:@"placeholder.png"]];



需要注意的是,pladeholderImage的大小一定要大于UIImageView的大小,否则可能不显示placeholderImage图片。

它还支持block语法用于在加载完成时做一些操作:


[cell.imageView setImageWithURL:[NSURL URLWithString:@"            http://www.domain.com/path/to/image.jpg            "]


              placeholderImage:[UIImage imageNamed:@"placeholder.png"]


                     completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {... completion code here ...}];



SDWebImage并不局限于UIImageView上,使用SDWebImageManager完成更多的操作:


SDWebImageManager *manager = [SDWebImageManager sharedManager];


[manager downloadWithURL:imageURL


                options:0


                progress:^(NSUInteger receivedSize,long long expectedSize)


                {


                    // 下载进度


                }


                completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)


                {


                    if (image)


                    {


                        // 下载完成


                    }


                }];



或者使用Image Downloader也是一样的效果:


[SDWebImageDownloader.sharedDownloader downloadImageWithURL:imageURL


       options:0


      progress:^(NSUInteger receivedSize,long long expectedSize)


      {


          // 进度


      }


      completed:^(UIImage *image, NSData *data, NSError *error,BOOL finished)


      {


          if (image && finished)


          {


              // 下载完成


          }


      }];




UIActivityIndicator-for-SDWebImage 为SDWebImage显示加载效果

GitHub:https://github.com/JJSaccolo/UIActivityIndicator-for-SDWebImage

用于为SDWebImage在UIImageView加载图片时,显示加载效果(UIActivityIndicatorView实现),它提供以下方法:


- (void)setImageWithURL:(NSURL *)url usingActivityIndicatorStyle:(UIActivityIndicatorViewStyle)activityStyle;


- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder usingActivityIndicatorStyle:(UIActivityIndicatorViewStyle)activityStyle;


- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options usingActivityIndicatorStyle:(UIActivityIndicatorViewStyle)activityStyle;


- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock usingActivityIndicatorStyle:(UIActivityIndicatorViewStyle)activityStyle;


- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock usingActivityIndicatorStyle:(UIActivityIndicatorViewStyle)activityStyle;


- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock usingActivityIndicatorStyle:(UIActivityIndicatorViewStyle)activityStyle;


- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock usingActivityIndicatorStyle:(UIActivityIndicatorViewStyle)activityStyle;




UIImage+Resize 调整图片大小

GitHub:https://github.com/coryalder/UIImage_Resize

提供多种方法为图片设置透明度、圆角、裁剪、调整大小等:


- (UIImage *)imageWithAlpha;


- (UIImage *)transparentBorderImage:(NSUInteger)borderSize;


- (UIImage *)roundedCornerImage:(NSInteger)cornerSize borderSize:(NSInteger)borderSize;


- (UIImage *)croppedImage:(CGRect)bounds;


- (UIImage *)thumbnailImage:(NSInteger)thumbnailSize


         transparentBorder:(NSUInteger)borderSize


              cornerRadius:(NSUInteger)cornerRadius


      interpolationQuality:(CGInterpolationQuality)quality;


- (UIImage *)resizedImage:(CGSize)newSize


    interpolationQuality:(CGInterpolationQuality)quality;


- (UIImage *)


 resizedImageWithContentMode:(UIViewContentMode)contentMode


                      bounds:(CGSize)bounds


        interpolationQuality:(CGInterpolationQuality)quality;



更详细使用见:http://vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/



ImageCacheResize 异步加载图片、缓存及调整大小

GitHub:https://github.com/toptierlabs/ImageCacheResize

整合了SDWebImage和UIImage+Resize的功能,用于图片的异步加载、缓存、以及下载完成后调整大小并显示在UIImageView上。

提供了以下API用于加载图片以及加载完成后调整图片大小:


- (void)setImageWithURL:(NSURL *)url andCropToBounds:(CGRect)bounds;


- (void)setImageWithURL:(NSURL *)url andResize:(CGSize)size withContentMode:(UIViewContentMode)mode;


- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder andCropToBounds:(CGRect)bounds;


- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options 


- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options 


- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options



使用方法和SDWebImage一样简单,如以下官方例子:

[imageview setImageWithURL:[NSURL URLWithString:@"            http://t0.gstatic.com/images?q=tbn:ANd9GcQfraHpiabjEY8iDdBe9OUQYHMtwfuAv9ZRR0RYKuoVF_EpE8Fp5A            "] andResize:CGSizeMake(30, 30) withContentMode:UIViewContentModeScaleAspectFit]; // 按比例缩放


[imageview setImageWithURL:[NSURL URLWithString:@"            http://t0.gstatic.com/images?q=tbn:ANd9GcQfraHpiabjEY8iDdBe9OUQYHMtwfuAv9ZRR0RYKuoVF_EpE8Fp5A            "] andCropToBounds:CGRectMake(0, 0, 100, 100)]; // 裁剪成100x100大小



举报

相关推荐

0 条评论