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

1.通过pod安装promisekit:

2. promise.h介绍

  1. @import Foundation.NSObject;
  2.  
  3. typedef void (^PromiseResolver)(id);
  4.  
  5. /**
  6. A `Promise` represents the future value of a task.
  7.  
  8. 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.
  9.  
  10. 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.
  11.  
  12. For a thorough overview of Promises, @see http://promisekit.org
  13. */
  14. @interface Promise : NSObject
  15.  
  16. /**
  17. The pattern of Promises is defined by the method: `then`.
  18.  
  19. 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.
  20.  
  21. Returning from your block will resolve the next `Promise` with that value.
  22.  
  23. 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.
  24.  
  25. @return A new `Promise` to be executed after the block passed to this `then`
  26. */
  27. - (Promise *(^)(id))then;
  28.  
  29. - (Promise *(^)(id))catch;
  30.  
  31. /**
  32. Returns a new Promise that is resolved when all passed Promises are resolved.
  33.  
  34. 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.
  35.  
  36. 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.
  37.  
  38. 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.
  39.  
  40. @param promiseOrArrayOfPromisesOrValue an array of Promises, a single Promise or a single value of any type.
  41. */
  42. + (Promise *)when:(id)promiseOrArrayOfPromisesOrValue;
  43.  
  44. /**
  45. Loops until one or more promises have resolved.
  46.  
  47. 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.
  48.  
  49. If the `catch` throws or returns an `NSError` then the loop is ended.
  50.  
  51. 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.
  52.  
  53. 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.
  54. */
  55. + (Promise *)until:(id(^)(void))blockReturningPromiseOrArrayOfPromises catch:(id)catchHandler;
  56.  
  57. /**
  58. Create a new root Promise.
  59.  
  60. 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.
  61. */
  62. + (Promise *)new:(void(^)(PromiseResolver fulfiller, PromiseResolver rejecter))block;
  63.  
  64. /**
  65. @return A new `Promise` that is already resolved with @param value. Calling `then` on a resolved `Promise` executes the provided block immediately.
  66. */
  67. + (Promise *)promiseWithValue:(id)value;
  68. @end
  69.  
  70. #define PMKErrorDomain @"PMKErrorDomain"
  71. #define PMKThrown @"PMKThrown"
  72. #define PMKErrorCodeThrown 1
  73. #define PMKErrorCodeUnknown 2
  74. #define PMKErrorCodeInvalidUsage 3
  75.  
  76. /**
  77. Executes @param block via `dispatch_async` with `DISPATCH_QUEUE_PRIORITY_DEFAULT`.
  78.  
  79. 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.
  80.  
  81. @param block A block to be executed in the background.
  82. @return A new `Promise` to be executed after @param block.
  83. */
  84. Promise *dispatch_promise(id block);
  85.  
  86. @import Dispatch.queue;
  87.  
  88. /**
  89. Executes @param block via `dispatch_async` on the specified queue.
  90. @see dispatch_promise
  91. */
  92. Promise *dispatch_promise_on(dispatch_queue_t q, id block);

3.使用流程

  1. NSString *imageURL = @"http://b.hiphotos.baidu.com/image/pic/item/d788d43f8794a4c23c175c2a0cf41bd5ad6e39fe.jpg";
  2.  
  3. /*!
  4. * GCD
  5. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  6.  
  7. NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
  8. dispatch_async(dispatch_get_main_queue(), ^{
  9. self.TKImageview.image = [[UIImage alloc]initWithData:data];
  10. });
  11. });
  12.  
  13. */
  14.  
  15. /*!
  16. * promiseKit
  17. */
  18. dispatch_promise(^{
  19. return imageURL;
  20. }).then(^(NSString *md5){
  21. return [NSURLConnection GET:@"%@",md5];
  22. }).then(^(UIImage *gravatarImage){
  23. self.TKImageview.image = gravatarImage;
  24. });
  25.  
  26. [NSURLConnection GET:@"http://promisekit.org"].then(^(NSData *data){
  27.  
  28. }).catch(^(NSError *error){
  29. NSHTTPURLResponse *rsp = error.userInfo[PMKURLErrorFailingURLResponse];
  30. int HTTPStatusCode = rsp.statusCode;
  31. });
  1. void (^errorHandler)(NSError *) = ^(NSError *error){
  2. NSLog(@"error : %@",error.userInfo);
  3. };
  4. NSURLRequest *rq = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://promisekit.org/"]];
  5. [NSURLConnection sendAsynchronousRequest:rq queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
  6. if (connectionError) {
  7. errorHandler(connectionError);
  8. } else {
  9. id jsonError;
  10. id json = [NSJSONSerialization JSONObjectWithData:data options: error:&jsonError];
  11. if (jsonError) {
  12. errorHandler(jsonError);
  13. } else {
  14. NSLog(@"%@",json);
  15. /*
  16. id home = [json valueForKeyPath:@"user.home.address"];
  17. [[CLGeocoder new] geocodeAddressString:home completionHandler:^(NSArray *placemarks, NSError *error) {
  18. if (error) {
  19. errorHandler(error);
  20. } else {
  21. MKDirectionsRequest *rq = [MKDirectionsRequest new];
  22. rq.source = [MKMapItem mapItemForCurrentLocation];
  23. rq.destination = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithPlacemark:placemarks[0]]];
  24. MKDirections *directions = [[MKDirections alloc] initWithRequest:rq];
  25. [directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
  26. if (error) {
  27. errorHandler(error);
  28. } else {
  29. //…
  30. }
  31. }];
  32. }
  33. }];
  34. */
  35. }
  36. }
  37. }];

参考地址:

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. [洛谷2397]yyy loves Maths VI

    题目背景 自动上次redbag用加法好好的刁难过了yyy同学以后,yyy十分愤怒.他还击给了redbag一题,但是这题他惊讶的发现自己居然也不会,所以只好找你 题目描述 他让redbag找众数他还特意 ...

  2. centos解决ping unknown host的问题

    当ping www.baidu.com 的时候如果出现 unknown host的提示 再ping一下IP, ping 8.8.8.8 如果此时能ping通,那么就是DNS服务器没有设置,不能解析域名 ...

  3. 华为2015 简单 字典输入法 java

    题目摘自http://blog.csdn.net/dongyi91/article/details/38639915 写了2个小时,水平太菜了 入法的编码原理为:根据已有编码表,当输入拼音和数字后输出 ...

  4. 单调栈 二 nyOj 最大矩形和

    主要思想来自 http://blog.csdn.net/wuyanyi/article/details/7243580 题目的连接,头次提交的同学需要注册 http://acm.nyist.net/J ...

  5. 关于Eclispse连接Mysql的Jdbc

    1.在Eclipse中新建Java工程 2.引入JDBC库(在bulid path 的extenrnal里) 3. 1)导入sql包(import java.sql.*) 2)加载(注册)mysql ...

  6. MapReduce自定义类输出的内容为内存地址

    13480253104 mapreduce.KpiWritable@486a58c4 13502468823 mapreduce.KpiWritable@3de9d100 13560439658 ma ...

  7. MySql避免全表扫描

    对查询进行优化,应尽量避免全表扫描,首先应考虑在where 及order by 涉及的列上建立索引: .尝试下面的技巧以避免优化器错选了表扫描: · 使用ANALYZE TABLE tbl_name为 ...

  8. A Tour of Go Nil slices

    The zero value of a slice is nil. A nil slice has a length and capacity of 0. (To learn more about s ...

  9. github上值得关注的前端项目

    https://segmentfault.com/a/1190000002804472

  10. MSSQLSERVER数据库- 解决不允许保存更改表结构

    工具菜单----选项----Designers(设计器)----阻止保存要求重新创建表的更改 取消勾选