ref links:
http://blog.mugunthkumar.com/products/ios-framework-introducing-mknetworkkit/
http://www.cocoachina.com/bbs/simple/?t93181.html
它包含了检测网络的代码 "Reachability" (http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html),用来检测网络是否reachable,以及网络是3g还是wifi。
它支持ARC feature
它是ASIHTTPRequest and AFNetworking的混合体,另外还提供一些其他features。
With MKNetworkKit, it’s hard to write ugly networking code. 即使用MKNetworkKit写出的代码会很优雅
Download
http://github.com/mugunthkumar/mknetworkkit
Installation
- 把MKNetworkKit lib添加到你的project。解压之后,把整个"MKNetworkKit“目录拖到Xcode里你的project的root node上,在弹出的窗口里tick "copy items into destination group's folder" option, select "create groups for any added folders" option, tick your project in "Add to targets" option, click "Finish".
- 添加4个framework: CFNetwork.Framework, SystemConfiguration.framework, Security.framework and ImageIO.framework: select project root node, 在旁边的panel选择"Targets"的node,select "Build Phases" tab, expand "Link binary with Libraries", click "+" button to add these 4 frameworks。添加之后,这3个frameworks会添加在project root node下,建议把它们move to "Frameworks" folder
- 在"Supporting Files"目录下的xxx-Prefix.pch file里添加下列代码
#import"MKNetworkKit.h"
- Delete MKNetworkKit/Categories/NSAlert+MKNetworkKitAdditions.h and .m fileif you are building for iOS.
- Delete MKNetworkKit/Categories/UIAlertView+MKNetworkKitAdditions.h and .m fileif you are building for Mac.
* MKNetworkKit好像使用Reachability不当,apple建议是在第一次连接失败后才check reachability,而MkNetworkKit是在初始化MKNetworkEngine时,初次连接之前就check reachability。(ref link: https://github.com/MugunthKumar/MKNetworkKit/issues/19)
最简单的使用MKNetworkKit的代码 (把下面代码复制到ViewController的viewDidLoad method里)
MKNetworkEngine *engine=[[MKNetworkEngine alloc] initWithHostName:@"download.finance.yahoo.com" customHeaderFields:nil];
MKNetworkOperation *op = [engine operationWithPath:@"d/quotes.csv?e=.csv&f=sl1d1t1&s=SGDUSD=X"
params:nil
httpMethod:@"GET"];
[op onCompletion:^(MKNetworkOperation *completedOperation)
{
DLog(@"Data from server %@", [completedOperation responseString]);
}onError:^(NSError* error) {
DLog("error: %@",error.description);
}];
[engine enqueueOperation:op];
注意:其实MKNetworkKit不建议直接在viewcontroller里直接使用MKNetworkEngine and MKNetworkOperation这2个classes,而应该创建一个MKNetworkEngine的子类,并把http operation都写在该子类里,viewcontroler则通过调用该子类来进行http操作(viewcontroller传递给子类的是一个回调block,这样当http operation complete时就通过这个block来通知view controller。相见MKNetworkKit examples里的viewcontroller.m and YahooEngine.m files)
下面是一个比较完整的例子。它是通过2个open source lib: MKNetworkKit and MBProgressHud来获取web page content。它包括以下几个features:
1. 异步
2. check internet connection reachability
3. show loading progress
如果要查看MKNetworkKit如何处理response format为json的例子,参看http://blog.csdn.net/totogogo/article/details/7402870
前提:add MKNetworkKit and MBProgressHud to your project
1. 在view controller .h file里实现<MBProgressHUDDelegate>
#import"MBProgressHUD.h"
@interface ViewController :UIViewController <MBProgressHUDDelegate>
2. 在view controller .m file里添加下列代码
- (IBAction)getCapHomePageContent:(id)sender {
MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
[self.view addSubview:hud];
// Regiser for HUD callbacks so we can remove it from the window at the right time
hud.delegate = self;
//show pregress hud
[hud show:YES];
[[CAPHttpService alloc] getCapHomePageContent:^(NSMutableArray *newsTitleList) {
//hide pregress hud
[hud hide:YES];
//todo: handle var newsTitleList
} onError:^(NSError* error) {
//hide pregress hud
[hud hide:YES];
//show alert window for error
if(error.code==-1009) //means no internet connection
{
[[[UIAlertView alloc] initWithTitle:@"Cannot Get Data"
message:@"Cannot get data because it could not connect to the server"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
} else {
[[[UIAlertView alloc] initWithTitle:@"Error"
message:[NSString stringWithFormat:@"Error code: %@", error.code]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
}
}];
}
既然实现"<MBProgressHUDDelegate>" 接口,就要添加"hudWasHidden" method,该方法是一个回调方法,当你执行"[hud hide:YES];"时,就会回调它
- (void)hudWasHidden:(MBProgressHUD *)hud {
// Remove HUD from screen when the HUD was hidded
[hud removeFromSuperview];
hud = nil;
}
3. 创建一个objective c class (假设为CAPHttpService),用于处理http request and response
CAPHttpService.h
#import <Foundation/Foundation.h>
@interface CAPHttpService : NSObject
typedef void (^NewsTitleListResponseBlock)(NSMutableArray *newsTitleList);
-(void) getCapHomePageContent:(NewsTitleListResponseBlock) completion
onError:(MKNKErrorBlock) error;
@end
CAPHttpService.m
#import "CAPHttpService.h"
@implementation CAPHttpService
-(void) getCapHomePageContent:(NewsTitleListResponseBlock) completion
onError:(MKNKErrorBlock) handleError{
MKNetworkEngine *engine=[[MKNetworkEngine alloc] initWithHostName:@"cap.cityu.edu.hk" customHeaderFields:nil];
MKNetworkOperation *op=[engine operationWithPath:@"studentlan/"
params:nil
httpMethod:@"GET"
ssl:1];
[op onCompletion:^(MKNetworkOperation *operation) {
DLog(@"%@", [operation responseStringWithEncoding:NSUTF8StringEncoding]);
//todo: parse var "operation" to news title list
NSMutableArray *newsTitleList=nil;
completion(newsTitleList);
}
onError:handleError
];
[engine enqueueOperation:op];
}
@end
注意认真理解CAPHttpService.m里getCapHomePageContent的定义和在viewcontroller里对其的调用,可以看到使用block,使得代码变得优雅!