简介:
高级开发是高度异步的,PromiseKit收集了一些帮助函数,让我们开发过程中使用的典型异步模式更加令人愉悦。

1.通过pod安装promisekit:

2. promise.h介绍

@import Foundation.NSObject;

typedef void (^PromiseResolver)(id);

/**
A `Promise` represents the future value of a task. To obtain the value of a `Promise`, call `then`. When the asynchronous task that this `Promise` represents has resolved successfully, the block you pass to `then` will be executed with the resolved value. If the `Promise` has already been resolved succesfully at the time you `then` the `Promise`, the block will be executed immediately. Effective use of Promises involves chaining `then`s, where the return value from one `then` is fed as the value of the next, et cetera. For a thorough overview of Promises, @see http://promisekit.org
*/
@interface Promise : NSObject /**
The pattern of Promises is defined by the method: `then`. Provide a block to `then`, your block may take one or no arguments, and return an object or have no return value. We use block introspection to provide such flexibility. Returning from your block will resolve the next `Promise` with that value. If an exception is thrown inside your block, or you return an `NSError` object the next `Promise` will be rejected. @see `catch` for documentation on error handling. @return A new `Promise` to be executed after the block passed to this `then`
*/
- (Promise *(^)(id))then; - (Promise *(^)(id))catch; /**
Returns a new Promise that is resolved when all passed Promises are resolved. If an array is passed then the returned `Promise` is resolved once all of the `Promise`s in the array are resolved. The returned Promise is rejected if *any* of the `Promise`s received by `when` fail. The returned `Promise` is resolved with an array of results indexed as the original array passed to when. If you pass a single value to when, you will not get an array in subsequent `then`s. Any `catch` handler will be called with a single `NSError` where the `PMKThrown` key of its `userInfo` will be an array of results. The results usually is a mixed array of `NSError`s and non-errors since usually not all the `Promise`s fail. @param promiseOrArrayOfPromisesOrValue an array of Promises, a single Promise or a single value of any type.
*/
+ (Promise *)when:(id)promiseOrArrayOfPromisesOrValue; /**
Loops until one or more promises have resolved. Because Promises are single-shot, the block to until must return one or more promises. They are then `when`’d. If they succeed the until loop is concluded. If they fail then the @param `catch` handler is executed. If the `catch` throws or returns an `NSError` then the loop is ended. If the `catch` handler returns a Promise then re-execution of the loop is suspended upon resolution of that Promise. If the Promise succeeds then the loop continues. If it fails the loop ends. An example usage is an app starting up that must get data from the Internet before the main ViewController can be shown. You can `until` the poll Promise and in the catch handler decide if the poll should be reattempted or not, perhaps returning a `UIAlertView.promise` allowing the user to choose if they continue or not.
*/
+ (Promise *)until:(id(^)(void))blockReturningPromiseOrArrayOfPromises catch:(id)catchHandler; /**
Create a new root Promise. Pass a block to this constructor, the block must take two arguments that point to the `fulfiller` and `rejecter` of this Promise. Fulfill or reject this Promise using those blocks and the Promise chain that roots to this Promise will be resolved accordingly.
*/
+ (Promise *)new:(void(^)(PromiseResolver fulfiller, PromiseResolver rejecter))block; /**
@return A new `Promise` that is already resolved with @param value. Calling `then` on a resolved `Promise` executes the provided block immediately.
*/
+ (Promise *)promiseWithValue:(id)value;
@end #define PMKErrorDomain @"PMKErrorDomain"
#define PMKThrown @"PMKThrown"
#define PMKErrorCodeThrown 1
#define PMKErrorCodeUnknown 2
#define PMKErrorCodeInvalidUsage 3 /**
Executes @param block via `dispatch_async` with `DISPATCH_QUEUE_PRIORITY_DEFAULT`. The returned `Promise` is resolved with the value returned from @param block (if any). Any `then` or `catch` attached to the returned `Promise` is exectued on the main queue. @param block A block to be executed in the background.
@return A new `Promise` to be executed after @param block.
*/
Promise *dispatch_promise(id block); @import Dispatch.queue; /**
Executes @param block via `dispatch_async` on the specified queue.
@see dispatch_promise
*/
Promise *dispatch_promise_on(dispatch_queue_t q, id block);

3.使用流程

 NSString *imageURL = @"http://b.hiphotos.baidu.com/image/pic/item/d788d43f8794a4c23c175c2a0cf41bd5ad6e39fe.jpg";

    /*!
* GCD
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
dispatch_async(dispatch_get_main_queue(), ^{
self.TKImageview.image = [[UIImage alloc]initWithData:data];
});
}); */ /*!
* promiseKit
*/
dispatch_promise(^{
return imageURL;
}).then(^(NSString *md5){
return [NSURLConnection GET:@"%@",md5];
}).then(^(UIImage *gravatarImage){
self.TKImageview.image = gravatarImage;
}); [NSURLConnection GET:@"http://promisekit.org"].then(^(NSData *data){ }).catch(^(NSError *error){
NSHTTPURLResponse *rsp = error.userInfo[PMKURLErrorFailingURLResponse];
int HTTPStatusCode = rsp.statusCode;
});
    void (^errorHandler)(NSError *) = ^(NSError *error){
NSLog(@"error : %@",error.userInfo);
};
NSURLRequest *rq = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://promisekit.org/"]];
[NSURLConnection sendAsynchronousRequest:rq queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) {
errorHandler(connectionError);
} else {
id jsonError;
id json = [NSJSONSerialization JSONObjectWithData:data options: error:&jsonError];
if (jsonError) {
errorHandler(jsonError);
} else {
NSLog(@"%@",json);
/*
id home = [json valueForKeyPath:@"user.home.address"];
[[CLGeocoder new] geocodeAddressString:home completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
errorHandler(error);
} else {
MKDirectionsRequest *rq = [MKDirectionsRequest new];
rq.source = [MKMapItem mapItemForCurrentLocation];
rq.destination = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithPlacemark:placemarks[0]]];
MKDirections *directions = [[MKDirections alloc] initWithRequest:rq];
[directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
if (error) {
errorHandler(error);
} else {
//…
}
}];
}
}];
*/
}
}
}];

参考地址:

http://promisekit.org/

https://github.com/mxcl/PromiseKit

ios PromiseKit的更多相关文章

  1. iOS 线程操作库 PromiseKit

    iOS 线程操作库 PromiseKit 官网:http://promisekit.org/ github:https://github.com/mxcl/PromiseKit/tree/master ...

  2. 【转】GitHub 排名前 100 的安卓、iOS项目简介

    GitHub Android Libraries Top 100 简介 排名完全是根据 GitHub 搜索 Java 语言选择 (Best Match) 得到的结果, 然后过滤了跟 Android 不 ...

  3. iOS 架构模式--解密 MVC,MVP,MVVM以及VIPER架构

    本文由CocoaChina译者lynulzy(社区ID)翻译 作者:Bohdan Orlov 原文:iOS Architecture Patterns 在 iOS 中使用 MVC 架构感觉很奇怪? 迁 ...

  4. iOS 资源大全

    这是个精心编排的列表,它包含了优秀的 iOS 框架.库.教程.XCode 插件.组件等等. 这个列表分为以下几个部分:框架( Frameworks ).组件( Components ).测试( Tes ...

  5. GitHub Top 100 的项目(iOS)

    主要对当前 GitHub 排名前 100 的项目做一个简单的简介, 方便初学者快速了解到当前 Objective-C 在 GitHub 的情况. Android 版本的在此: https://gith ...

  6. 盘点国内程序员不常用的热门iOS第三方库:看完,还敢自称”精通iOS开发”吗?【转载】

    综合github上各个项目的关注度与具体使用情况,涵盖功能,UI,数据库,自动化测试,编程工具等类型,看完,还敢自称”精通iOS开发”吗? https://github.com/syedhali/EZ ...

  7. 2016年GitHub 排名前 100 的安卓、iOS项目简介(收藏)

    排名完全是根据 GitHub 搜索 Java 语言选择 (Best Match) 得到的结果, 然后过滤了跟 Android 不相关的项目, 所以排名并不具备任何官方效力, 仅供参考学习, 方便初学者 ...

  8. iOS.OpenSource.AllInOne

    Open Source Project for iOS 所有和iOS相关的Open Source Project的汇总. 功能点 开源项目   iOS Gallery RMGallery https: ...

  9. GitHub上排名前100的iOS开源库介绍(来自github)

    主要对当前 GitHub 排名前 100 的项目做一个简单的简介,方便初学者快速了解到当前 Objective-C 在 GitHub 的情况. 若有任何疑问可通过微博@李锦发联系我 项目名称 项目信息 ...

随机推荐

  1. [King.yue]关于CSLA框架的一些看法

    CSLA.Net 是一个有帮助的成熟开发框架,但不适于初学者.该框架支持在任何地方.任何时间创建对象,值得我们花时间去学习了解这一框架.CSLA.Net 框架设计的业务对象,支持对完全透明的数据源进行 ...

  2. 提升WI-FI信号强度的10大方法

    原文链接:http://server.51cto.com/Net-402889.htm

  3. 2015年9月29日html基础加强学习笔记

    创建一个最简便的浏览器 首先打开VS2010,然后在空间里拖出一个Form控件当主页面,其次拖出一个Textbox控件作为地址栏,然后加一个Button控件作为按钮,最后拖出一个WebBrowser作 ...

  4. platform机制

    最近在看SPI.I2C这样简单点的总线驱动程 序,从Linux2.6起,内核引入了一套新的驱动管理和注册机制:Platform_device和Platform_driver.现在Linux中 大部分的 ...

  5. 输入n个数组,数组长度不等,每个数组取出一个数进行组合,求出所有的组合。

    转载声明:原文转自http://www.cnblogs.com/xiezie/p/5511707.html 昨天晚上,有个朋友找到我,他在用matlab编程,但是遇到一个问题,解决不了. 问题如下: ...

  6. CF_402C Searching for Graph 乱搞题

    题目链接:http://codeforces.com/problemset/problem/402/C /**算法分析: 乱搞题,不明白题目想考什么 */ #include<bits/stdc+ ...

  7. Java NIO 缓冲技术详解

    缓冲区(buffer)是从即将写入通道(channel)或刚刚从通道中读出的一段数据.它是一个持有数据,并扮演NIO通道端点的对象.缓冲区为数据访问和读写过程提供正式机制. 它是NIO和老版Java ...

  8. hdoj 1898 Sempr == The Best Problem Solver?

    Sempr == The Best Problem Solver? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65535/3276 ...

  9. T-SQL语句查看作业等信息

    因服务器需要迁移,需要将现有JOB迁移至新服务器,待服务器调整完毕,则重新迁移到原服务器,所以在做迁移之前希望将现有JOB进行备份,不至于乱了执行时间.1.查看所有作业列表USE master SEL ...

  10. 以管理员身份启动ClickOnce部署的应用程序

    ClickOnce方式部署应用简单方便,估计很多人都用过,但这种方式存在一定的“缺陷”,即以管理员方式启动应用的问题,虽然出于安全考虑可以理解,但给需要管理员权限才能正常运行的程序带来了一定的麻烦,这 ...