iOS: a promising http connection framework - MKNetworkKit

原创 2012年03月27日 00:56:19

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

  1. 把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".
  2. 添加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
  3. 在"Supporting Files"目录下的xxx-Prefix.pch file里添加下列代码   

    #import"MKNetworkKit.h"


  4. Delete MKNetworkKit/Categories/NSAlert+MKNetworkKitAdditions.h and .m fileif you are building for iOS.
  5. Delete MKNetworkKit/Categories/UIAlertView+MKNetworkKitAdditions.h and .m fileif you are building for Mac.
6. build your project


* 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,使得代码变得优雅!



iOS Framework: Introducing MKNetworkKit

什么是 MKNetworkKit? MKNetworkKit 是一个用objective-c写的网络库,具有无缝连接,基于block,ARC支持以及易用等特点。 MKNetworkKit的灵感来自...

iOS http框架的介绍:用MKNetworkKit/AFNetworking 代替/替代/VS ASIHTTPRequest

ASIHTTPRequest (作者:BenCopsey) 是一个使用简单,可用于各种从简单到复杂的 HTTP 请求,或者可用于处理 Amazon S3、Rackspace 等REST 服务的强大框架...

iOS: NSUrlConnection & SSL, Http connection frameworks

java有一个httpclient open source lib来进行http connection操作,android就是使用它 iOS自身是通过NSUrlConnection来进行ht...

iOS Framework: Introducing MKNetworkKit (MKNetworkKit介绍,入门,翻译)

这片文章也有塞尔维亚-克罗地亚语(由Jovana Milutinovich翻译)和日语(由@noradaiko翻译) 如果有个一个网络库能够自动的为你处理cache该有多好啊。 如果有...

【无线互联】ios开发之MKNetworkKit的介绍和使用

XXX

MKNetworkkit uses features only available in iOS SDK 4.0 and later

导入第三方库MKNetworkKit出错 MKNetworkKit uses features only available in iOS SDK 4.0 and later报错解决方案 ...

IOS:MKNetworkKit的网络请求(使用封装好的类)

既然看到本文章,至少你已经对MKNetworkKit不是太陌生了。那就废话少说,直接上代码。 yi...

IOS使用MKNetworkKit框架实现下载数据和上传数据

MKNetworkOperation类不仅可以指定下载文件的位置,还可以获得下载的进度,由于它采用整个应用共享单一队列的设计,所以可以准确地计算下载进度。话不多说,下面通过一个例子来说明下载数据和上传...

MKNetworkKit uses features only available in iOS SDK 4.0 and later报错解决方案

MKNetworkKit uses features only available in iOS SDK 4.0 and later报错解决方案 MKNetworkKit是一个非常优秀的网络请求框架...

ios MKNetworkKit 的使用

常用框架比如:AFNetworking,ASIHttpRequest,SDWebImage,MKNetWorKit等。 iOS5已出来这么久了,而ASIHttpRequest的作者已经申明不更新...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:iOS: a promising http connection framework - MKNetworkKit
举报原因:
原因补充:

(最多只允许输入30个字)