├── README.md
├── WaveLoadingView.xcodeproj
├── project.pbxproj
├── project.xcworkspace
│ ├── contents.xcworkspacedata
│ └── xcuserdata
│ │ └── lzy.xcuserdatad
│ │ └── xcdebugger
│ │ └── Expressions.xcexplist
└── xcuserdata
│ └── lzy.xcuserdatad
│ ├── xcdebugger
│ └── Breakpoints_v2.xcbkptlist
│ └── xcschemes
│ ├── WaveLoadingView.xcscheme
│ └── xcschememanagement.plist
├── WaveLoadingView
├── 2016-01-17 17_36_30.gif
├── 2016-01-19 00_30_06.gif
├── 2016-01-19 10_26_10.gif
├── AppDelegate.swift
├── Assets.xcassets
│ ├── AppIcon.appiconset
│ │ └── Contents.json
│ ├── Contents.json
│ └── shadow.imageset
│ │ ├── Contents.json
│ │ └── shadow.png
├── Base.lproj
│ ├── LaunchScreen.storyboard
│ └── Main.storyboard
├── Classes
│ ├── DisplayViewController.swift
│ ├── DisplayViewController.xib
│ └── WaveLoadingIndicator.swift
├── Info.plist
├── SDWebImage
│ ├── NSData+ImageContentType.h
│ ├── NSData+ImageContentType.m
│ ├── SDImageCache.h
│ ├── SDImageCache.m
│ ├── SDWebImageCompat.h
│ ├── SDWebImageCompat.m
│ ├── SDWebImageDecoder.h
│ ├── SDWebImageDecoder.m
│ ├── SDWebImageDownloader.h
│ ├── SDWebImageDownloader.m
│ ├── SDWebImageDownloaderOperation.h
│ ├── SDWebImageDownloaderOperation.m
│ ├── SDWebImageManager.h
│ ├── SDWebImageManager.m
│ ├── SDWebImageOperation.h
│ ├── SDWebImagePrefetcher.h
│ ├── SDWebImagePrefetcher.m
│ ├── UIButton+WebCache.h
│ ├── UIButton+WebCache.m
│ ├── UIImage+GIF.h
│ ├── UIImage+GIF.m
│ ├── UIImage+MultiFormat.h
│ ├── UIImage+MultiFormat.m
│ ├── UIImageView+HighlightedWebCache.h
│ ├── UIImageView+HighlightedWebCache.m
│ ├── UIImageView+WebCache.h
│ ├── UIImageView+WebCache.m
│ ├── UIView+WebCacheOperation.h
│ └── UIView+WebCacheOperation.m
├── ViewController.swift
├── WaveloadingView-Bridging-Header.h
└── perform.gif
├── WaveLoadingViewTests
├── Info.plist
└── WaveLoadingViewTests.swift
└── WaveLoadingViewUITests
├── Info.plist
└── WaveLoadingViewUITests.swift
/README.md:
--------------------------------------------------------------------------------
1 | # WaveLoadingView
2 | A loading indicator like water wave
3 |
4 | ###You can play a demo with [appetize.io](https://appetize.io/app/9upnjbk9hwjaz9hjyzuz41788c?device=iphone5s&scale=75&orientation=portrait&osVersion=9.2)
5 |
6 |
7 |
8 | #**Features:**
9 |
10 | 
11 |
12 |
13 | #**Property:**
14 | - cycle —— 循环次数,在控件宽度范围内,该正弦函数图形循环的次数,数值越大控件范围内看见的正弦函数图形周期数越多,波长约短波浪也越陡。
15 | - term —— 正弦周期,在layoutSubviews中根据cycle重新计算,==修改无效==
16 | - phasePosition —— 正弦函数相位,==不可修改==,否则图形错乱
17 | - amplitude —— 波幅,数值越大,波浪幅度越大,波浪越陡,反之越平缓,可通过代码调用`waveAmplitude`修改
18 | - position —— 正弦曲线的X轴 相对于 控件Y坐标的位置,在-drawRect中通过progress计算,==修改无效==
19 | - waveMoveSpan —— 波浪移动的单位跨度,数值越大波浪移动越快,数值过大会出现不连续动画现象
20 | - animationUnitTime —— 重画单位时间,数值越小,重画速度越快频率越大
21 | - heavyColor —— demo中较深的绿色部分
22 | - lightColor —— demo中较浅的绿色部分
23 | - clipCircleColor —— 玻璃球边界颜色
24 | - clipCircleLineWidth —— 玻璃球边线宽度,可通过代码调用`borderWidth`修改
25 | - progressTextFontSize —— 中央进度提示百分比字号大小
26 |
27 |
28 |
29 | #**Usage:**
30 | 1. include the file WaveLoadingView.swift to your project, and about objectiveC, you can create a bridge Header and import it
31 | 2. creat a waveLoadingIndicator instance
32 | ```swift
33 | let waveLoadingIndicator: WaveLoadingIndicator = WaveLoadingIndicator(frame: CGRectZero)
34 | ```
35 | 3. add waveLoadingIndicator to your imageView, equal bounds here i do , and FlexibleWidth,height
36 | ```swift
37 | self.displayImageView.addSubview(self.waveLoadingIndicator)
38 | self.waveLoadingIndicator.frame = self.displayImageView.bounds
39 | self.waveLoadingIndicator.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
40 | ```
41 | 4. and your can used combine with SDWebImage:
42 | ```swift
43 | self.displayImageView.sd_setImageWithURL(url, placeholderImage: nil, options: .CacheMemoryOnly, progress: {
44 | [weak self](receivedSize, expectedSize) -> Void in
45 |
46 | guard let weakSelf = self else {
47 | return
48 | }
49 |
50 | weakSelf.waveLoadingIndicator.progress = Double(CGFloat(receivedSize)/CGFloat(expectedSize))
51 | }) {
52 | [weak self](image, error, _, _) -> Void in
53 | // 不要忘记在完成下载回调中,移除waveLoadingIndicator
54 | guard let weakSelf = self else {
55 | return
56 | }
57 |
58 | weakSelf.waveLoadingIndicator.removeFromSuperview()
59 | }
60 | ```
61 | >
62 | > Don't worry, after -removeFromSuperview(), the animation have been stop
63 |
64 | ##Relation
65 | [@liuzhiyi1992](https://github.com/liuzhiyi1992) on Github
66 | [WaveLoadingIndicator](http://zyden.vicp.cc/waveloadingindicator/) in my Blog
67 |
68 |
69 |
70 | #**License:**
71 | WaveLoadingIndicator is available under the MIT license. See the LICENSE file for more info.
72 |
--------------------------------------------------------------------------------
/WaveLoadingView.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/WaveLoadingView.xcodeproj/project.xcworkspace/xcuserdata/lzy.xcuserdatad/xcdebugger/Expressions.xcexplist:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
7 |
8 |
10 |
11 |
13 |
14 |
15 |
16 |
18 |
19 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/WaveLoadingView.xcodeproj/xcuserdata/lzy.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
--------------------------------------------------------------------------------
/WaveLoadingView.xcodeproj/xcuserdata/lzy.xcuserdatad/xcschemes/WaveLoadingView.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
33 |
39 |
40 |
41 |
43 |
49 |
50 |
51 |
52 |
53 |
59 |
60 |
61 |
62 |
63 |
64 |
74 |
76 |
82 |
83 |
84 |
85 |
86 |
87 |
93 |
95 |
101 |
102 |
103 |
104 |
106 |
107 |
110 |
111 |
112 |
--------------------------------------------------------------------------------
/WaveLoadingView.xcodeproj/xcuserdata/lzy.xcuserdatad/xcschemes/xcschememanagement.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | SchemeUserState
6 |
7 | WaveLoadingView.xcscheme
8 |
9 | orderHint
10 | 0
11 |
12 |
13 | SuppressBuildableAutocreation
14 |
15 | 48A33AB61C33D3F500BB179C
16 |
17 | primary
18 |
19 |
20 | 48A33ACA1C33D3F500BB179C
21 |
22 | primary
23 |
24 |
25 | 48A33AD51C33D3F500BB179C
26 |
27 | primary
28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/WaveLoadingView/2016-01-17 17_36_30.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/liuzhiyi1992/WaveLoadingView/b8acc7f4af94921f4038d1a2516a45aed2fa5fce/WaveLoadingView/2016-01-17 17_36_30.gif
--------------------------------------------------------------------------------
/WaveLoadingView/2016-01-19 00_30_06.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/liuzhiyi1992/WaveLoadingView/b8acc7f4af94921f4038d1a2516a45aed2fa5fce/WaveLoadingView/2016-01-19 00_30_06.gif
--------------------------------------------------------------------------------
/WaveLoadingView/2016-01-19 10_26_10.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/liuzhiyi1992/WaveLoadingView/b8acc7f4af94921f4038d1a2516a45aed2fa5fce/WaveLoadingView/2016-01-19 10_26_10.gif
--------------------------------------------------------------------------------
/WaveLoadingView/AppDelegate.swift:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.swift
3 | // WaveLoadingView
4 | //
5 | // Created by lzy on 15/12/30.
6 | // Copyright © 2015年 lzy. All rights reserved.
7 | //
8 |
9 | import UIKit
10 |
11 | @UIApplicationMain
12 | class AppDelegate: UIResponder, UIApplicationDelegate {
13 |
14 | var window: UIWindow?
15 |
16 |
17 | func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
18 | // Override point for customization after application launch.
19 | return true
20 | }
21 |
22 | func applicationWillResignActive(application: UIApplication) {
23 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
24 | // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
25 | }
26 |
27 | func applicationDidEnterBackground(application: UIApplication) {
28 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
29 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
30 | }
31 |
32 | func applicationWillEnterForeground(application: UIApplication) {
33 | // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
34 | }
35 |
36 | func applicationDidBecomeActive(application: UIApplication) {
37 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
38 | }
39 |
40 | func applicationWillTerminate(application: UIApplication) {
41 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
42 | }
43 |
44 | }
45 |
46 | // 版权属于原作者
47 | // 个人博客 zyden.vicp.cc
48 |
49 |
--------------------------------------------------------------------------------
/WaveLoadingView/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "size" : "29x29",
6 | "scale" : "2x"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "size" : "29x29",
11 | "scale" : "3x"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "size" : "40x40",
16 | "scale" : "2x"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "size" : "40x40",
21 | "scale" : "3x"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "size" : "60x60",
26 | "scale" : "2x"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "size" : "60x60",
31 | "scale" : "3x"
32 | }
33 | ],
34 | "info" : {
35 | "version" : 1,
36 | "author" : "xcode"
37 | }
38 | }
--------------------------------------------------------------------------------
/WaveLoadingView/Assets.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "version" : 1,
4 | "author" : "xcode"
5 | }
6 | }
--------------------------------------------------------------------------------
/WaveLoadingView/Assets.xcassets/shadow.imageset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "universal",
5 | "scale" : "1x"
6 | },
7 | {
8 | "idiom" : "universal",
9 | "filename" : "shadow.png",
10 | "scale" : "2x"
11 | },
12 | {
13 | "idiom" : "universal",
14 | "scale" : "3x"
15 | }
16 | ],
17 | "info" : {
18 | "version" : 1,
19 | "author" : "xcode"
20 | }
21 | }
--------------------------------------------------------------------------------
/WaveLoadingView/Assets.xcassets/shadow.imageset/shadow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/liuzhiyi1992/WaveLoadingView/b8acc7f4af94921f4038d1a2516a45aed2fa5fce/WaveLoadingView/Assets.xcassets/shadow.imageset/shadow.png
--------------------------------------------------------------------------------
/WaveLoadingView/Base.lproj/LaunchScreen.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/WaveLoadingView/Base.lproj/Main.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
70 |
76 |
87 |
98 |
109 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
--------------------------------------------------------------------------------
/WaveLoadingView/Classes/DisplayViewController.swift:
--------------------------------------------------------------------------------
1 | //
2 | // DisplayViewController.swift
3 | // WaveLoadingView
4 | //
5 | // Created by lzy on 16/1/17.
6 | // Copyright © 2016年 lzy. All rights reserved.
7 | //
8 |
9 | import UIKit
10 |
11 | class DisplayViewController: UIViewController {
12 |
13 | @IBOutlet weak var displayImageView: UIImageView!
14 | let waveLoadingIndicator: WaveLoadingIndicator = WaveLoadingIndicator(frame: CGRectZero)
15 |
16 | // let url = NSURL(string: "http://www.quyundong.com/uploads/1080_1920.jpg")
17 | let url = NSURL(string: "https://raw.githubusercontent.com/liuzhiyi1992/MyStore/master/DSC_0865.JPG")
18 |
19 |
20 | override func viewDidLoad() {
21 | super.viewDidLoad()
22 | configure()
23 | }
24 |
25 |
26 | func configure() {
27 | self.displayImageView.addSubview(self.waveLoadingIndicator)
28 | self.waveLoadingIndicator.frame = self.displayImageView.bounds
29 | self.waveLoadingIndicator.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
30 | self.displayImageView.sd_setImageWithURL(url, placeholderImage: nil, options: .CacheMemoryOnly, progress: {
31 | [weak self](receivedSize, expectedSize) -> Void in
32 |
33 | guard let weakSelf = self else {
34 | return
35 | }
36 |
37 | weakSelf.waveLoadingIndicator.progress = Double(CGFloat(receivedSize)/CGFloat(expectedSize))
38 | }) {
39 | [weak self](image, error, _, _) -> Void in
40 |
41 | guard let weakSelf = self else {
42 | return
43 | }
44 |
45 | weakSelf.waveLoadingIndicator.removeFromSuperview()
46 | }
47 | }
48 |
49 |
50 | override func didReceiveMemoryWarning() {
51 | super.didReceiveMemoryWarning()
52 | // Dispose of any resources that can be recreated.
53 | }
54 |
55 | }
56 |
57 | // 版权属于原作者
58 | // 个人博客 zyden.vicp.cc
59 |
60 |
--------------------------------------------------------------------------------
/WaveLoadingView/Classes/DisplayViewController.xib:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/WaveLoadingView/Classes/WaveLoadingIndicator.swift:
--------------------------------------------------------------------------------
1 | //
2 | // WaveLoadingIndicator.swift
3 | // WaveLoadingView
4 | //
5 | // Created by lzy on 15/12/30.
6 | // Copyright © 2015年 lzy. All rights reserved.
7 | //
8 |
9 | //正弦函数公式 y = amplitude * sin((2 * π / term) * x +- phasePosition)
10 | import UIKit
11 |
12 |
13 | let π = M_PI
14 |
15 | enum ShapeModel {
16 | case shapeModelCircle
17 | case shapeModelRect
18 | }
19 |
20 |
21 | class WaveLoadingIndicator: UIView {
22 |
23 | var originX = 0.0//X坐标起点, the x origin of wave
24 | static private let amplitude_min = 16.0//波幅最小值
25 | static private let amplitude_span = 26.0//波幅可调节幅度
26 |
27 | private let cycle = 1.0//循环次数, num of circulation
28 | private var term = 60.0//周期(在代码中重新计算), recalculate in layoutSubviews
29 | private var phasePosition = 0.0//相位必须为0(画曲线机制局限), phase Must be 0
30 | private var amplitude = 29.0//波幅
31 | private var position = 40.0//X轴所在的Y坐标(在代码中重新计算), where the x axis of wave position
32 |
33 | private let waveMoveSpan = 5.0//波浪移动单位跨度, the span wave move in a unit time
34 | private let animationUnitTime = 0.08//重画单位时间, redraw unit time
35 |
36 | private let heavyColor = UIColor(red: 38/255.0, green: 227/255.0, blue: 198/255.0, alpha: 1.0)
37 | private let lightColor = UIColor(red: 121/255.0, green: 248/255.0, blue: 221/255.0, alpha: 1.0)
38 | private let clipCircleColor = UIColor(red: 38/255.0, green: 227/255.0, blue: 198/255.0, alpha: 1.0)
39 |
40 | private var clipCircleLineWidth: CGFloat = 1
41 |
42 | private let progressTextFontSize: CGFloat = 15.0
43 |
44 | private var waving: Bool = true
45 |
46 |
47 | class var amplitudeMin: Double {
48 | get { return amplitude_min }
49 | }
50 | class var amplitudeSpan: Double {
51 | get { return amplitude_span }
52 | }
53 |
54 | var progress: Double = 0.5 {
55 | didSet {
56 | self.setNeedsDisplay()
57 | }
58 | }
59 |
60 | var waveAmplitude: Double {
61 | get { return amplitude }
62 | set {
63 | amplitude = newValue
64 | self.setNeedsDisplay()
65 | }
66 | }
67 |
68 | var borderWidth: CGFloat {
69 | get { return clipCircleLineWidth }
70 | set {
71 | clipCircleLineWidth = newValue
72 | self.setNeedsDisplay()
73 | }
74 | }
75 |
76 | var isShowProgressText = true
77 |
78 | var shapeModel:ShapeModel = .shapeModelCircle
79 |
80 |
81 |
82 | //if use not in xib, create an func init
83 | override func awakeFromNib() {
84 | animationWave()
85 | self.backgroundColor = UIColor.clearColor()
86 | }
87 |
88 | override init(frame: CGRect) {
89 | super.init(frame: frame)
90 | animationWave()
91 | self.backgroundColor = UIColor.clearColor()
92 | }
93 |
94 | required init?(coder aDecoder: NSCoder) {
95 | super.init(coder: aDecoder)
96 | // fatalError("init(coder:) has not been implemented")
97 | }
98 |
99 | deinit {
100 | }
101 |
102 | override func drawRect(rect: CGRect) {
103 | position = (1 - progress) * Double(rect.height)
104 |
105 | //circle clip
106 | clipWithCircle()
107 |
108 | //draw wave
109 | drawWaveWater(originX - term / 5, fillColor: lightColor)
110 | drawWaveWater(originX, fillColor: heavyColor)
111 |
112 | //Let clipCircle above the waves
113 | clipWithCircle()
114 |
115 | //draw the tip text of progress
116 | if isShowProgressText {
117 | drawProgressText()
118 | }
119 | }
120 |
121 | override func layoutSubviews() {
122 | super.layoutSubviews()
123 | //计算周期calculate the term
124 | term = Double(self.bounds.size.width) / cycle
125 | }
126 |
127 | override func removeFromSuperview() {
128 | super.removeFromSuperview()
129 | waving = false
130 | }
131 |
132 | func clipWithCircle() {
133 | let circleRectWidth = min(self.bounds.size.width, self.bounds.size.height) - 2 * clipCircleLineWidth
134 | let circleRectOriginX = (self.bounds.size.width - circleRectWidth) / 2
135 | let circleRectOriginY = (self.bounds.size.height - circleRectWidth) / 2
136 | let circleRect = CGRectMake(circleRectOriginX, circleRectOriginY, circleRectWidth, circleRectWidth)
137 |
138 | var clipPath: UIBezierPath!
139 | if shapeModel == .shapeModelCircle {
140 | clipPath = UIBezierPath(ovalInRect: circleRect)
141 | } else if shapeModel == .shapeModelRect {
142 | clipPath = UIBezierPath(rect: circleRect)
143 | }
144 |
145 | clipCircleColor.setStroke()
146 | clipPath.lineWidth = clipCircleLineWidth
147 | clipPath.stroke()
148 | clipPath.addClip()
149 | }
150 |
151 |
152 | func drawWaveWater(originX: Double, fillColor: UIColor) {
153 | let curvePath = UIBezierPath()
154 | curvePath.moveToPoint(CGPoint(x: originX, y: position))
155 |
156 | //循环,画波浪wave path
157 | var tempPoint = originX
158 | for _ in 1...rounding(4 * cycle) {//(2 * cycle)即可充满屏幕,即一个循环,为了移动画布使波浪移动,我们要画两个循环
159 | curvePath.addQuadCurveToPoint(keyPoint(tempPoint + term / 2, originX: originX), controlPoint: keyPoint(tempPoint + term / 4, originX: originX))
160 | tempPoint += term / 2
161 | }
162 |
163 | //close the water path
164 | curvePath.addLineToPoint(CGPoint(x: curvePath.currentPoint.x, y: self.bounds.size.height))
165 | curvePath.addLineToPoint(CGPoint(x: CGFloat(originX), y: self.bounds.size.height))
166 | curvePath.closePath()
167 |
168 | fillColor.setFill()
169 | curvePath.lineWidth = 10
170 | curvePath.fill()
171 | }
172 |
173 |
174 | func drawProgressText() {
175 | //Avoid negative
176 | var validProgress = progress * 100
177 | validProgress = validProgress < 1 ? 0 : validProgress
178 |
179 | let progressText = (NSString(format: "%.0f", validProgress) as String) + "%"
180 |
181 | var attribute: [String : AnyObject]!
182 | if progress > 0.45 {
183 | attribute = [NSFontAttributeName : UIFont.systemFontOfSize(progressTextFontSize), NSForegroundColorAttributeName : UIColor.whiteColor()]
184 | } else {
185 | attribute = [NSFontAttributeName : UIFont.systemFontOfSize(progressTextFontSize), NSForegroundColorAttributeName : heavyColor]
186 | }
187 |
188 | let textSize = progressText.sizeWithAttributes(attribute)
189 | let textRect = CGRectMake(self.bounds.width/2 - textSize.width/2, self.bounds.height/2 - textSize.height/2, textSize.width, textSize.height)
190 |
191 | progressText.drawInRect(textRect, withAttributes: attribute)
192 | }
193 |
194 |
195 | func animationWave() {
196 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { [weak self]() -> Void in
197 | if self != nil {
198 | let tempOriginX = self!.originX
199 | while self != nil && self!.waving {
200 | if self!.originX <= tempOriginX - self!.term {
201 | self!.originX = tempOriginX - self!.waveMoveSpan
202 | } else {
203 | self!.originX -= self!.waveMoveSpan
204 | }
205 | dispatch_async(dispatch_get_main_queue(), { () -> Void in
206 | self!.setNeedsDisplay()
207 | })
208 | NSThread.sleepForTimeInterval(self!.animationUnitTime)
209 | }
210 | }
211 | }
212 | }
213 |
214 |
215 | //determine the key point of curve
216 | func keyPoint(x: Double, originX: Double) -> CGPoint {
217 | //x为当前取点x坐标,columnYPoint的参数为相对于正弦函数原点的x坐标
218 | return CGPoint(x: x, y: columnYPoint(x - originX))
219 | }
220 |
221 |
222 | func columnYPoint(x: Double) -> Double {
223 | //三角正弦函数
224 | let result = amplitude * sin((2 * π / term) * x + phasePosition)
225 | return result + position
226 | }
227 |
228 | //四舍五入
229 | func rounding(value: Double) -> Int {
230 | let tempInt = Int(value)
231 | let tempDouble = Double(tempInt) + 0.5
232 | if value > tempDouble {
233 | return tempInt + 1
234 | } else {
235 | return tempInt
236 | }
237 | }
238 |
239 |
240 | }
241 |
242 | // 版权属于原作者
243 | // 个人博客 zyden.vicp.cc
244 |
--------------------------------------------------------------------------------
/WaveLoadingView/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | APPL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 | LSRequiresIPhoneOS
24 |
25 | NSAppTransportSecurity
26 |
27 | NSAllowsArbitraryLoads
28 |
29 |
30 | UILaunchStoryboardName
31 | LaunchScreen
32 | UIMainStoryboardFile
33 | Main
34 | UIRequiredDeviceCapabilities
35 |
36 | armv7
37 |
38 | UISupportedInterfaceOrientations
39 |
40 | UIInterfaceOrientationPortrait
41 | UIInterfaceOrientationLandscapeLeft
42 | UIInterfaceOrientationLandscapeRight
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/NSData+ImageContentType.h:
--------------------------------------------------------------------------------
1 | //
2 | // Created by Fabrice Aneche on 06/01/14.
3 | // Copyright (c) 2014 Dailymotion. All rights reserved.
4 | //
5 |
6 | #import
7 |
8 | @interface NSData (ImageContentType)
9 |
10 | /**
11 | * Compute the content type for an image data
12 | *
13 | * @param data the input data
14 | *
15 | * @return the content type as string (i.e. image/jpeg, image/gif)
16 | */
17 | + (NSString *)sd_contentTypeForImageData:(NSData *)data;
18 |
19 | @end
20 |
21 |
22 | @interface NSData (ImageContentTypeDeprecated)
23 |
24 | + (NSString *)contentTypeForImageData:(NSData *)data __deprecated_msg("Use `sd_contentTypeForImageData:`");
25 |
26 | @end
27 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/NSData+ImageContentType.m:
--------------------------------------------------------------------------------
1 | //
2 | // Created by Fabrice Aneche on 06/01/14.
3 | // Copyright (c) 2014 Dailymotion. All rights reserved.
4 | //
5 |
6 | #import "NSData+ImageContentType.h"
7 |
8 |
9 | @implementation NSData (ImageContentType)
10 |
11 | + (NSString *)sd_contentTypeForImageData:(NSData *)data {
12 | uint8_t c;
13 | [data getBytes:&c length:1];
14 | switch (c) {
15 | case 0xFF:
16 | return @"image/jpeg";
17 | case 0x89:
18 | return @"image/png";
19 | case 0x47:
20 | return @"image/gif";
21 | case 0x49:
22 | case 0x4D:
23 | return @"image/tiff";
24 | case 0x52:
25 | // R as RIFF for WEBP
26 | if ([data length] < 12) {
27 | return nil;
28 | }
29 |
30 | NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
31 | if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
32 | return @"image/webp";
33 | }
34 |
35 | return nil;
36 | }
37 | return nil;
38 | }
39 |
40 | @end
41 |
42 |
43 | @implementation NSData (ImageContentTypeDeprecated)
44 |
45 | + (NSString *)contentTypeForImageData:(NSData *)data {
46 | return [self sd_contentTypeForImageData:data];
47 | }
48 |
49 | @end
50 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/SDImageCache.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import
10 | #import "SDWebImageCompat.h"
11 |
12 | typedef NS_ENUM(NSInteger, SDImageCacheType) {
13 | /**
14 | * The image wasn't available the SDWebImage caches, but was downloaded from the web.
15 | */
16 | SDImageCacheTypeNone,
17 | /**
18 | * The image was obtained from the disk cache.
19 | */
20 | SDImageCacheTypeDisk,
21 | /**
22 | * The image was obtained from the memory cache.
23 | */
24 | SDImageCacheTypeMemory
25 | };
26 |
27 | typedef void(^SDWebImageQueryCompletedBlock)(UIImage *image, SDImageCacheType cacheType);
28 |
29 | typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache);
30 |
31 | typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize);
32 |
33 | /**
34 | * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed
35 | * asynchronous so it doesn’t add unnecessary latency to the UI.
36 | */
37 | @interface SDImageCache : NSObject
38 |
39 | /**
40 | * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory.
41 | */
42 | @property (assign, nonatomic) NSUInteger maxMemoryCost;
43 |
44 | /**
45 | * The maximum length of time to keep an image in the cache, in seconds
46 | */
47 | @property (assign, nonatomic) NSInteger maxCacheAge;
48 |
49 | /**
50 | * The maximum size of the cache, in bytes.
51 | */
52 | @property (assign, nonatomic) NSUInteger maxCacheSize;
53 |
54 | /**
55 | * Returns global shared cache instance
56 | *
57 | * @return SDImageCache global instance
58 | */
59 | + (SDImageCache *)sharedImageCache;
60 |
61 | /**
62 | * Init a new cache store with a specific namespace
63 | *
64 | * @param ns The namespace to use for this cache store
65 | */
66 | - (id)initWithNamespace:(NSString *)ns;
67 |
68 | /**
69 | * Add a read-only cache path to search for images pre-cached by SDImageCache
70 | * Useful if you want to bundle pre-loaded images with your app
71 | *
72 | * @param path The path to use for this read-only cache path
73 | */
74 | - (void)addReadOnlyCachePath:(NSString *)path;
75 |
76 | /**
77 | * Store an image into memory and disk cache at the given key.
78 | *
79 | * @param image The image to store
80 | * @param key The unique image cache key, usually it's image absolute URL
81 | */
82 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key;
83 |
84 | /**
85 | * Store an image into memory and optionally disk cache at the given key.
86 | *
87 | * @param image The image to store
88 | * @param key The unique image cache key, usually it's image absolute URL
89 | * @param toDisk Store the image to disk cache if YES
90 | */
91 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk;
92 |
93 | /**
94 | * Store an image into memory and optionally disk cache at the given key.
95 | *
96 | * @param image The image to store
97 | * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage
98 | * @param imageData The image data as returned by the server, this representation will be used for disk storage
99 | * instead of converting the given image object into a storable/compressed image format in order
100 | * to save quality and CPU
101 | * @param key The unique image cache key, usually it's image absolute URL
102 | * @param toDisk Store the image to disk cache if YES
103 | */
104 | - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk;
105 |
106 | /**
107 | * Query the disk cache asynchronously.
108 | *
109 | * @param key The unique key used to store the wanted image
110 | */
111 | - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock;
112 |
113 | /**
114 | * Query the memory cache synchronously.
115 | *
116 | * @param key The unique key used to store the wanted image
117 | */
118 | - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key;
119 |
120 | /**
121 | * Query the disk cache synchronously after checking the memory cache.
122 | *
123 | * @param key The unique key used to store the wanted image
124 | */
125 | - (UIImage *)imageFromDiskCacheForKey:(NSString *)key;
126 |
127 | /**
128 | * Remove the image from memory and disk cache synchronously
129 | *
130 | * @param key The unique image cache key
131 | */
132 | - (void)removeImageForKey:(NSString *)key;
133 |
134 |
135 | /**
136 | * Remove the image from memory and disk cache synchronously
137 | *
138 | * @param key The unique image cache key
139 | * @param completionBlock An block that should be executed after the image has been removed (optional)
140 | */
141 | - (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion;
142 |
143 | /**
144 | * Remove the image from memory and optionally disk cache synchronously
145 | *
146 | * @param key The unique image cache key
147 | * @param fromDisk Also remove cache entry from disk if YES
148 | */
149 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk;
150 |
151 | /**
152 | * Remove the image from memory and optionally disk cache synchronously
153 | *
154 | * @param key The unique image cache key
155 | * @param fromDisk Also remove cache entry from disk if YES
156 | * @param completionBlock An block that should be executed after the image has been removed (optional)
157 | */
158 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion;
159 |
160 | /**
161 | * Clear all memory cached images
162 | */
163 | - (void)clearMemory;
164 |
165 | /**
166 | * Clear all disk cached images. Non-blocking method - returns immediately.
167 | * @param completionBlock An block that should be executed after cache expiration completes (optional)
168 | */
169 | - (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion;
170 |
171 | /**
172 | * Clear all disk cached images
173 | * @see clearDiskOnCompletion:
174 | */
175 | - (void)clearDisk;
176 |
177 | /**
178 | * Remove all expired cached image from disk. Non-blocking method - returns immediately.
179 | * @param completionBlock An block that should be executed after cache expiration completes (optional)
180 | */
181 | - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock;
182 |
183 | /**
184 | * Remove all expired cached image from disk
185 | * @see cleanDiskWithCompletionBlock:
186 | */
187 | - (void)cleanDisk;
188 |
189 | /**
190 | * Get the size used by the disk cache
191 | */
192 | - (NSUInteger)getSize;
193 |
194 | /**
195 | * Get the number of images in the disk cache
196 | */
197 | - (NSUInteger)getDiskCount;
198 |
199 | /**
200 | * Asynchronously calculate the disk cache's size.
201 | */
202 | - (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock;
203 |
204 | /**
205 | * Async check if image exists in disk cache already (does not load the image)
206 | *
207 | * @param key the key describing the url
208 | * @param completionBlock the block to be executed when the check is done.
209 | * @note the completion block will be always executed on the main queue
210 | */
211 | - (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;
212 |
213 | /**
214 | * Check if image exists in disk cache already (does not load the image)
215 | *
216 | * @param key the key describing the url
217 | *
218 | * @return YES if an image exists for the given key
219 | */
220 | - (BOOL)diskImageExistsWithKey:(NSString *)key;
221 |
222 | /**
223 | * Get the cache path for a certain key (needs the cache path root folder)
224 | *
225 | * @param key the key (can be obtained from url using cacheKeyForURL)
226 | * @param path the cach path root folder
227 | *
228 | * @return the cache path
229 | */
230 | - (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path;
231 |
232 | /**
233 | * Get the default cache path for a certain key
234 | *
235 | * @param key the key (can be obtained from url using cacheKeyForURL)
236 | *
237 | * @return the default cache path
238 | */
239 | - (NSString *)defaultCachePathForKey:(NSString *)key;
240 |
241 | @end
242 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/SDWebImageCompat.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | * (c) Jamie Pinkham
5 | *
6 | * For the full copyright and license information, please view the LICENSE
7 | * file that was distributed with this source code.
8 | */
9 |
10 | #import
11 |
12 | #ifdef __OBJC_GC__
13 | #error SDWebImage does not support Objective-C Garbage Collection
14 | #endif
15 |
16 | #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0
17 | #error SDWebImage doesn't support Deployement Target version < 5.0
18 | #endif
19 |
20 | #if !TARGET_OS_IPHONE
21 | #import
22 | #ifndef UIImage
23 | #define UIImage NSImage
24 | #endif
25 | #ifndef UIImageView
26 | #define UIImageView NSImageView
27 | #endif
28 | #else
29 |
30 | #import
31 |
32 | #endif
33 |
34 | #ifndef NS_ENUM
35 | #define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
36 | #endif
37 |
38 | #ifndef NS_OPTIONS
39 | #define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type
40 | #endif
41 |
42 | #if OS_OBJECT_USE_OBJC
43 | #undef SDDispatchQueueRelease
44 | #undef SDDispatchQueueSetterSementics
45 | #define SDDispatchQueueRelease(q)
46 | #define SDDispatchQueueSetterSementics strong
47 | #else
48 | #undef SDDispatchQueueRelease
49 | #undef SDDispatchQueueSetterSementics
50 | #define SDDispatchQueueRelease(q) (dispatch_release(q))
51 | #define SDDispatchQueueSetterSementics assign
52 | #endif
53 |
54 | extern UIImage *SDScaledImageForKey(NSString *key, UIImage *image);
55 |
56 | typedef void(^SDWebImageNoParamsBlock)();
57 |
58 | #define dispatch_main_sync_safe(block)\
59 | if ([NSThread isMainThread]) {\
60 | block();\
61 | } else {\
62 | dispatch_sync(dispatch_get_main_queue(), block);\
63 | }
64 |
65 | #define dispatch_main_async_safe(block)\
66 | if ([NSThread isMainThread]) {\
67 | block();\
68 | } else {\
69 | dispatch_async(dispatch_get_main_queue(), block);\
70 | }
71 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/SDWebImageCompat.m:
--------------------------------------------------------------------------------
1 | //
2 | // SDWebImageCompat.m
3 | // SDWebImage
4 | //
5 | // Created by Olivier Poitrey on 11/12/12.
6 | // Copyright (c) 2012 Dailymotion. All rights reserved.
7 | //
8 |
9 | #import "SDWebImageCompat.h"
10 |
11 | #if !__has_feature(objc_arc)
12 | #error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag
13 | #endif
14 |
15 | inline UIImage *SDScaledImageForKey(NSString *key, UIImage *image) {
16 | if (!image) {
17 | return nil;
18 | }
19 |
20 | if ([image.images count] > 0) {
21 | NSMutableArray *scaledImages = [NSMutableArray array];
22 |
23 | for (UIImage *tempImage in image.images) {
24 | [scaledImages addObject:SDScaledImageForKey(key, tempImage)];
25 | }
26 |
27 | return [UIImage animatedImageWithImages:scaledImages duration:image.duration];
28 | }
29 | else {
30 | if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
31 | CGFloat scale = 1.0;
32 | if (key.length >= 8) {
33 | // Search @2x. at the end of the string, before a 3 to 4 extension length (only if key len is 8 or more @2x. + 4 len ext)
34 | NSRange range = [key rangeOfString:@"@2x." options:0 range:NSMakeRange(key.length - 8, 5)];
35 | if (range.location != NSNotFound) {
36 | scale = 2.0;
37 | }
38 | }
39 |
40 | UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation];
41 | image = scaledImage;
42 | }
43 | return image;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/SDWebImageDecoder.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * Created by james on 9/28/11.
6 | *
7 | * For the full copyright and license information, please view the LICENSE
8 | * file that was distributed with this source code.
9 | */
10 |
11 | #import
12 | #import "SDWebImageCompat.h"
13 |
14 | @interface UIImage (ForceDecode)
15 |
16 | + (UIImage *)decodedImageWithImage:(UIImage *)image;
17 |
18 | @end
19 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/SDWebImageDecoder.m:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * Created by james on 9/28/11.
6 | *
7 | * For the full copyright and license information, please view the LICENSE
8 | * file that was distributed with this source code.
9 | */
10 |
11 | #import "SDWebImageDecoder.h"
12 |
13 | @implementation UIImage (ForceDecode)
14 |
15 | + (UIImage *)decodedImageWithImage:(UIImage *)image {
16 | if (image.images) {
17 | // Do not decode animated images
18 | return image;
19 | }
20 |
21 | CGImageRef imageRef = image.CGImage;
22 | CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef));
23 | CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize};
24 |
25 | CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
26 | CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
27 |
28 | int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask);
29 | BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone ||
30 | infoMask == kCGImageAlphaNoneSkipFirst ||
31 | infoMask == kCGImageAlphaNoneSkipLast);
32 |
33 | // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB.
34 | // https://developer.apple.com/library/mac/#qa/qa1037/_index.html
35 | if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) {
36 | // Unset the old alpha info.
37 | bitmapInfo &= ~kCGBitmapAlphaInfoMask;
38 |
39 | // Set noneSkipFirst.
40 | bitmapInfo |= kCGImageAlphaNoneSkipFirst;
41 | }
42 | // Some PNGs tell us they have alpha but only 3 components. Odd.
43 | else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) {
44 | // Unset the old alpha info.
45 | bitmapInfo &= ~kCGBitmapAlphaInfoMask;
46 | bitmapInfo |= kCGImageAlphaPremultipliedFirst;
47 | }
48 |
49 | // It calculates the bytes-per-row based on the bitsPerComponent and width arguments.
50 | CGContextRef context = CGBitmapContextCreate(NULL,
51 | imageSize.width,
52 | imageSize.height,
53 | CGImageGetBitsPerComponent(imageRef),
54 | 0,
55 | colorSpace,
56 | bitmapInfo);
57 | CGColorSpaceRelease(colorSpace);
58 |
59 | // If failed, return undecompressed image
60 | if (!context) return image;
61 |
62 | CGContextDrawImage(context, imageRect, imageRef);
63 | CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context);
64 |
65 | CGContextRelease(context);
66 |
67 | UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation];
68 | CGImageRelease(decompressedImageRef);
69 | return decompressedImage;
70 | }
71 |
72 | @end
73 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/SDWebImageDownloader.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import
10 | #import "SDWebImageCompat.h"
11 | #import "SDWebImageOperation.h"
12 |
13 | typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) {
14 | SDWebImageDownloaderLowPriority = 1 << 0,
15 | SDWebImageDownloaderProgressiveDownload = 1 << 1,
16 |
17 | /**
18 | * By default, request prevent the of NSURLCache. With this flag, NSURLCache
19 | * is used with default policies.
20 | */
21 | SDWebImageDownloaderUseNSURLCache = 1 << 2,
22 |
23 | /**
24 | * Call completion block with nil image/imageData if the image was read from NSURLCache
25 | * (to be combined with `SDWebImageDownloaderUseNSURLCache`).
26 | */
27 |
28 | SDWebImageDownloaderIgnoreCachedResponse = 1 << 3,
29 | /**
30 | * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for
31 | * extra time in background to let the request finish. If the background task expires the operation will be cancelled.
32 | */
33 |
34 | SDWebImageDownloaderContinueInBackground = 1 << 4,
35 |
36 | /**
37 | * Handles cookies stored in NSHTTPCookieStore by setting
38 | * NSMutableURLRequest.HTTPShouldHandleCookies = YES;
39 | */
40 | SDWebImageDownloaderHandleCookies = 1 << 5,
41 |
42 | /**
43 | * Enable to allow untrusted SSL ceriticates.
44 | * Useful for testing purposes. Use with caution in production.
45 | */
46 | SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6,
47 |
48 | /**
49 | * Put the image in the high priority queue.
50 | */
51 | SDWebImageDownloaderHighPriority = 1 << 7,
52 |
53 |
54 | };
55 |
56 | typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) {
57 | /**
58 | * Default value. All download operations will execute in queue style (first-in-first-out).
59 | */
60 | SDWebImageDownloaderFIFOExecutionOrder,
61 |
62 | /**
63 | * All download operations will execute in stack style (last-in-first-out).
64 | */
65 | SDWebImageDownloaderLIFOExecutionOrder
66 | };
67 |
68 | extern NSString *const SDWebImageDownloadStartNotification;
69 | extern NSString *const SDWebImageDownloadStopNotification;
70 |
71 | typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize);
72 |
73 | typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished);
74 |
75 | typedef NSDictionary *(^SDWebImageDownloaderHeadersFilterBlock)(NSURL *url, NSDictionary *headers);
76 |
77 | /**
78 | * Asynchronous downloader dedicated and optimized for image loading.
79 | */
80 | @interface SDWebImageDownloader : NSObject
81 |
82 | @property (assign, nonatomic) NSInteger maxConcurrentDownloads;
83 |
84 | /**
85 | * Shows the current amount of downloads that still need to be downloaded
86 | */
87 |
88 | @property (readonly, nonatomic) NSUInteger currentDownloadCount;
89 |
90 |
91 | /**
92 | * The timeout value (in seconds) for the download operation. Default: 15.0.
93 | */
94 | @property (assign, nonatomic) NSTimeInterval downloadTimeout;
95 |
96 |
97 | /**
98 | * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`.
99 | */
100 | @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder;
101 |
102 | /**
103 | * Singleton method, returns the shared instance
104 | *
105 | * @return global shared instance of downloader class
106 | */
107 | + (SDWebImageDownloader *)sharedDownloader;
108 |
109 | /**
110 | * Set username
111 | */
112 | @property (strong, nonatomic) NSString *username;
113 |
114 | /**
115 | * Set password
116 | */
117 | @property (strong, nonatomic) NSString *password;
118 |
119 | /**
120 | * Set filter to pick headers for downloading image HTTP request.
121 | *
122 | * This block will be invoked for each downloading image request, returned
123 | * NSDictionary will be used as headers in corresponding HTTP request.
124 | */
125 | @property (nonatomic, copy) SDWebImageDownloaderHeadersFilterBlock headersFilter;
126 |
127 | /**
128 | * Set a value for a HTTP header to be appended to each download HTTP request.
129 | *
130 | * @param value The value for the header field. Use `nil` value to remove the header.
131 | * @param field The name of the header field to set.
132 | */
133 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
134 |
135 | /**
136 | * Returns the value of the specified HTTP header field.
137 | *
138 | * @return The value associated with the header field field, or `nil` if there is no corresponding header field.
139 | */
140 | - (NSString *)valueForHTTPHeaderField:(NSString *)field;
141 |
142 | /**
143 | * Creates a SDWebImageDownloader async downloader instance with a given URL
144 | *
145 | * The delegate will be informed when the image is finish downloaded or an error has happen.
146 | *
147 | * @see SDWebImageDownloaderDelegate
148 | *
149 | * @param url The URL to the image to download
150 | * @param options The options to be used for this download
151 | * @param progressBlock A block called repeatedly while the image is downloading
152 | * @param completedBlock A block called once the download is completed.
153 | * If the download succeeded, the image parameter is set, in case of error,
154 | * error parameter is set with the error. The last parameter is always YES
155 | * if SDWebImageDownloaderProgressiveDownload isn't use. With the
156 | * SDWebImageDownloaderProgressiveDownload option, this block is called
157 | * repeatedly with the partial image object and the finished argument set to NO
158 | * before to be called a last time with the full image and finished argument
159 | * set to YES. In case of error, the finished argument is always YES.
160 | *
161 | * @return A cancellable SDWebImageOperation
162 | */
163 | - (id )downloadImageWithURL:(NSURL *)url
164 | options:(SDWebImageDownloaderOptions)options
165 | progress:(SDWebImageDownloaderProgressBlock)progressBlock
166 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock;
167 |
168 | /**
169 | * Sets the download queue suspension state
170 | */
171 | - (void)setSuspended:(BOOL)suspended;
172 |
173 | @end
174 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/SDWebImageDownloader.m:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import "SDWebImageDownloader.h"
10 | #import "SDWebImageDownloaderOperation.h"
11 | #import
12 |
13 | NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification";
14 | NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification";
15 |
16 | static NSString *const kProgressCallbackKey = @"progress";
17 | static NSString *const kCompletedCallbackKey = @"completed";
18 |
19 | @interface SDWebImageDownloader ()
20 |
21 | @property (strong, nonatomic) NSOperationQueue *downloadQueue;
22 | @property (weak, nonatomic) NSOperation *lastAddedOperation;
23 | @property (strong, nonatomic) NSMutableDictionary *URLCallbacks;
24 | @property (strong, nonatomic) NSMutableDictionary *HTTPHeaders;
25 | // This queue is used to serialize the handling of the network responses of all the download operation in a single queue
26 | @property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t barrierQueue;
27 |
28 | @end
29 |
30 | @implementation SDWebImageDownloader
31 |
32 | + (void)initialize {
33 | // Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator )
34 | // To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import
35 | if (NSClassFromString(@"SDNetworkActivityIndicator")) {
36 |
37 | #pragma clang diagnostic push
38 | #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
39 | id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")];
40 | #pragma clang diagnostic pop
41 |
42 | // Remove observer in case it was previously added.
43 | [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil];
44 | [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil];
45 |
46 | [[NSNotificationCenter defaultCenter] addObserver:activityIndicator
47 | selector:NSSelectorFromString(@"startActivity")
48 | name:SDWebImageDownloadStartNotification object:nil];
49 | [[NSNotificationCenter defaultCenter] addObserver:activityIndicator
50 | selector:NSSelectorFromString(@"stopActivity")
51 | name:SDWebImageDownloadStopNotification object:nil];
52 | }
53 | }
54 |
55 | + (SDWebImageDownloader *)sharedDownloader {
56 | static dispatch_once_t once;
57 | static id instance;
58 | dispatch_once(&once, ^{
59 | instance = [self new];
60 | });
61 | return instance;
62 | }
63 |
64 | - (id)init {
65 | if ((self = [super init])) {
66 | _executionOrder = SDWebImageDownloaderFIFOExecutionOrder;
67 | _downloadQueue = [NSOperationQueue new];
68 | _downloadQueue.maxConcurrentOperationCount = 2;
69 | _URLCallbacks = [NSMutableDictionary new];
70 | _HTTPHeaders = [NSMutableDictionary dictionaryWithObject:@"image/webp,image/*;q=0.8" forKey:@"Accept"];
71 | _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT);
72 | _downloadTimeout = 15.0;
73 | }
74 | return self;
75 | }
76 |
77 | - (void)dealloc {
78 | [self.downloadQueue cancelAllOperations];
79 | SDDispatchQueueRelease(_barrierQueue);
80 | }
81 |
82 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field {
83 | if (value) {
84 | self.HTTPHeaders[field] = value;
85 | }
86 | else {
87 | [self.HTTPHeaders removeObjectForKey:field];
88 | }
89 | }
90 |
91 | - (NSString *)valueForHTTPHeaderField:(NSString *)field {
92 | return self.HTTPHeaders[field];
93 | }
94 |
95 | - (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads {
96 | _downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads;
97 | }
98 |
99 | - (NSUInteger)currentDownloadCount {
100 | return _downloadQueue.operationCount;
101 | }
102 |
103 | - (NSInteger)maxConcurrentDownloads {
104 | return _downloadQueue.maxConcurrentOperationCount;
105 | }
106 |
107 | - (id )downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock {
108 | __block SDWebImageDownloaderOperation *operation;
109 | __weak SDWebImageDownloader *wself = self;
110 |
111 | [self addProgressCallback:progressBlock andCompletedBlock:completedBlock forURL:url createCallback:^{
112 | NSTimeInterval timeoutInterval = wself.downloadTimeout;
113 | if (timeoutInterval == 0.0) {
114 | timeoutInterval = 15.0;
115 | }
116 |
117 | // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise
118 | NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval];
119 | request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies);
120 | request.HTTPShouldUsePipelining = YES;
121 | if (wself.headersFilter) {
122 | request.allHTTPHeaderFields = wself.headersFilter(url, [wself.HTTPHeaders copy]);
123 | }
124 | else {
125 | request.allHTTPHeaderFields = wself.HTTPHeaders;
126 | }
127 | operation = [[SDWebImageDownloaderOperation alloc] initWithRequest:request
128 | options:options
129 | progress:^(NSInteger receivedSize, NSInteger expectedSize) {
130 | SDWebImageDownloader *sself = wself;
131 | if (!sself) return;
132 | NSArray *callbacksForURL = [sself callbacksForURL:url];
133 | for (NSDictionary *callbacks in callbacksForURL) {
134 | SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey];
135 | if (callback) callback(receivedSize, expectedSize);
136 | }
137 | }
138 | completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
139 | SDWebImageDownloader *sself = wself;
140 | if (!sself) return;
141 | NSArray *callbacksForURL = [sself callbacksForURL:url];
142 | if (finished) {
143 | [sself removeCallbacksForURL:url];
144 | }
145 | for (NSDictionary *callbacks in callbacksForURL) {
146 | SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey];
147 | if (callback) callback(image, data, error, finished);
148 | }
149 | }
150 | cancelled:^{
151 | SDWebImageDownloader *sself = wself;
152 | if (!sself) return;
153 | [sself removeCallbacksForURL:url];
154 | }];
155 |
156 | if (wself.username && wself.password) {
157 | operation.credential = [NSURLCredential credentialWithUser:wself.username password:wself.password persistence:NSURLCredentialPersistenceForSession];
158 | }
159 |
160 | if (options & SDWebImageDownloaderHighPriority) {
161 | operation.queuePriority = NSOperationQueuePriorityHigh;
162 | } else if (options & SDWebImageDownloaderLowPriority) {
163 | operation.queuePriority = NSOperationQueuePriorityLow;
164 | }
165 |
166 | [wself.downloadQueue addOperation:operation];
167 | if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) {
168 | // Emulate LIFO execution order by systematically adding new operations as last operation's dependency
169 | [wself.lastAddedOperation addDependency:operation];
170 | wself.lastAddedOperation = operation;
171 | }
172 | }];
173 |
174 | return operation;
175 | }
176 |
177 | - (void)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock andCompletedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock forURL:(NSURL *)url createCallback:(SDWebImageNoParamsBlock)createCallback {
178 | // The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data.
179 | if (url == nil) {
180 | if (completedBlock != nil) {
181 | completedBlock(nil, nil, nil, NO);
182 | }
183 | return;
184 | }
185 |
186 | dispatch_barrier_sync(self.barrierQueue, ^{
187 | BOOL first = NO;
188 | if (!self.URLCallbacks[url]) {
189 | self.URLCallbacks[url] = [NSMutableArray new];
190 | first = YES;
191 | }
192 |
193 | // Handle single download of simultaneous download request for the same URL
194 | NSMutableArray *callbacksForURL = self.URLCallbacks[url];
195 | NSMutableDictionary *callbacks = [NSMutableDictionary new];
196 | if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy];
197 | if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy];
198 | [callbacksForURL addObject:callbacks];
199 | self.URLCallbacks[url] = callbacksForURL;
200 |
201 | if (first) {
202 | createCallback();
203 | }
204 | });
205 | }
206 |
207 | - (NSArray *)callbacksForURL:(NSURL *)url {
208 | __block NSArray *callbacksForURL;
209 | dispatch_sync(self.barrierQueue, ^{
210 | callbacksForURL = self.URLCallbacks[url];
211 | });
212 | return [callbacksForURL copy];
213 | }
214 |
215 | - (void)removeCallbacksForURL:(NSURL *)url {
216 | dispatch_barrier_async(self.barrierQueue, ^{
217 | [self.URLCallbacks removeObjectForKey:url];
218 | });
219 | }
220 |
221 | - (void)setSuspended:(BOOL)suspended {
222 | [self.downloadQueue setSuspended:suspended];
223 | }
224 |
225 | @end
226 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/SDWebImageDownloaderOperation.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import
10 | #import "SDWebImageDownloader.h"
11 | #import "SDWebImageOperation.h"
12 |
13 | @interface SDWebImageDownloaderOperation : NSOperation
14 |
15 | /**
16 | * The request used by the operation's connection.
17 | */
18 | @property (strong, nonatomic, readonly) NSURLRequest *request;
19 |
20 | /**
21 | * Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default.
22 | *
23 | * This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`.
24 | */
25 | @property (nonatomic, assign) BOOL shouldUseCredentialStorage;
26 |
27 | /**
28 | * The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`.
29 | *
30 | * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
31 | */
32 | @property (nonatomic, strong) NSURLCredential *credential;
33 |
34 | /**
35 | * The SDWebImageDownloaderOptions for the receiver.
36 | */
37 | @property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options;
38 |
39 | /**
40 | * Initializes a `SDWebImageDownloaderOperation` object
41 | *
42 | * @see SDWebImageDownloaderOperation
43 | *
44 | * @param request the URL request
45 | * @param options downloader options
46 | * @param progressBlock the block executed when a new chunk of data arrives.
47 | * @note the progress block is executed on a background queue
48 | * @param completedBlock the block executed when the download is done.
49 | * @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue
50 | * @param cancelBlock the block executed if the download (operation) is cancelled
51 | *
52 | * @return the initialized instance
53 | */
54 | - (id)initWithRequest:(NSURLRequest *)request
55 | options:(SDWebImageDownloaderOptions)options
56 | progress:(SDWebImageDownloaderProgressBlock)progressBlock
57 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock
58 | cancelled:(SDWebImageNoParamsBlock)cancelBlock;
59 |
60 | @end
61 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/SDWebImageDownloaderOperation.m:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import "SDWebImageDownloaderOperation.h"
10 | #import "SDWebImageDecoder.h"
11 | #import "UIImage+MultiFormat.h"
12 | #import
13 | #import "SDWebImageManager.h"
14 |
15 | @interface SDWebImageDownloaderOperation ()
16 |
17 | @property (copy, nonatomic) SDWebImageDownloaderProgressBlock progressBlock;
18 | @property (copy, nonatomic) SDWebImageDownloaderCompletedBlock completedBlock;
19 | @property (copy, nonatomic) SDWebImageNoParamsBlock cancelBlock;
20 |
21 | @property (assign, nonatomic, getter = isExecuting) BOOL executing;
22 | @property (assign, nonatomic, getter = isFinished) BOOL finished;
23 | @property (assign, nonatomic) NSInteger expectedSize;
24 | @property (strong, nonatomic) NSMutableData *imageData;
25 | @property (strong, nonatomic) NSURLConnection *connection;
26 | @property (strong, atomic) NSThread *thread;
27 |
28 | #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
29 | @property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId;
30 | #endif
31 |
32 | @end
33 |
34 | @implementation SDWebImageDownloaderOperation {
35 | size_t width, height;
36 | UIImageOrientation orientation;
37 | BOOL responseFromCached;
38 | }
39 |
40 | @synthesize executing = _executing;
41 | @synthesize finished = _finished;
42 |
43 | - (id)initWithRequest:(NSURLRequest *)request
44 | options:(SDWebImageDownloaderOptions)options
45 | progress:(SDWebImageDownloaderProgressBlock)progressBlock
46 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock
47 | cancelled:(SDWebImageNoParamsBlock)cancelBlock {
48 | if ((self = [super init])) {
49 | _request = request;
50 | _shouldUseCredentialStorage = YES;
51 | _options = options;
52 | _progressBlock = [progressBlock copy];
53 | _completedBlock = [completedBlock copy];
54 | _cancelBlock = [cancelBlock copy];
55 | _executing = NO;
56 | _finished = NO;
57 | _expectedSize = 0;
58 | responseFromCached = YES; // Initially wrong until `connection:willCacheResponse:` is called or not called
59 | }
60 | return self;
61 | }
62 |
63 | - (void)start {
64 | @synchronized (self) {
65 | if (self.isCancelled) {
66 | self.finished = YES;
67 | [self reset];
68 | return;
69 | }
70 |
71 | #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
72 | if ([self shouldContinueWhenAppEntersBackground]) {
73 | __weak __typeof__ (self) wself = self;
74 | self.backgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
75 | __strong __typeof (wself) sself = wself;
76 |
77 | if (sself) {
78 | [sself cancel];
79 |
80 | [[UIApplication sharedApplication] endBackgroundTask:sself.backgroundTaskId];
81 | sself.backgroundTaskId = UIBackgroundTaskInvalid;
82 | }
83 | }];
84 | }
85 | #endif
86 |
87 | self.executing = YES;
88 | self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
89 | self.thread = [NSThread currentThread];
90 | }
91 |
92 | [self.connection start];
93 |
94 | if (self.connection) {
95 | if (self.progressBlock) {
96 | self.progressBlock(0, NSURLResponseUnknownLength);
97 | }
98 | [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:self];
99 |
100 | if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_5_1) {
101 | // Make sure to run the runloop in our background thread so it can process downloaded data
102 | // Note: we use a timeout to work around an issue with NSURLConnection cancel under iOS 5
103 | // not waking up the runloop, leading to dead threads (see https://github.com/rs/SDWebImage/issues/466)
104 | CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false);
105 | }
106 | else {
107 | CFRunLoopRun();
108 | }
109 |
110 | if (!self.isFinished) {
111 | [self.connection cancel];
112 | [self connection:self.connection didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorTimedOut userInfo:@{NSURLErrorFailingURLErrorKey : self.request.URL}]];
113 | }
114 | }
115 | else {
116 | if (self.completedBlock) {
117 | self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Connection can't be initialized"}], YES);
118 | }
119 | }
120 |
121 | #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
122 | if (self.backgroundTaskId != UIBackgroundTaskInvalid) {
123 | [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskId];
124 | self.backgroundTaskId = UIBackgroundTaskInvalid;
125 | }
126 | #endif
127 | }
128 |
129 | - (void)cancel {
130 | @synchronized (self) {
131 | if (self.thread) {
132 | [self performSelector:@selector(cancelInternalAndStop) onThread:self.thread withObject:nil waitUntilDone:NO];
133 | }
134 | else {
135 | [self cancelInternal];
136 | }
137 | }
138 | }
139 |
140 | - (void)cancelInternalAndStop {
141 | if (self.isFinished) return;
142 | [self cancelInternal];
143 | CFRunLoopStop(CFRunLoopGetCurrent());
144 | }
145 |
146 | - (void)cancelInternal {
147 | if (self.isFinished) return;
148 | [super cancel];
149 | if (self.cancelBlock) self.cancelBlock();
150 |
151 | if (self.connection) {
152 | [self.connection cancel];
153 | [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self];
154 |
155 | // As we cancelled the connection, its callback won't be called and thus won't
156 | // maintain the isFinished and isExecuting flags.
157 | if (self.isExecuting) self.executing = NO;
158 | if (!self.isFinished) self.finished = YES;
159 | }
160 |
161 | [self reset];
162 | }
163 |
164 | - (void)done {
165 | self.finished = YES;
166 | self.executing = NO;
167 | [self reset];
168 | }
169 |
170 | - (void)reset {
171 | self.cancelBlock = nil;
172 | self.completedBlock = nil;
173 | self.progressBlock = nil;
174 | self.connection = nil;
175 | self.imageData = nil;
176 | self.thread = nil;
177 | }
178 |
179 | - (void)setFinished:(BOOL)finished {
180 | [self willChangeValueForKey:@"isFinished"];
181 | _finished = finished;
182 | [self didChangeValueForKey:@"isFinished"];
183 | }
184 |
185 | - (void)setExecuting:(BOOL)executing {
186 | [self willChangeValueForKey:@"isExecuting"];
187 | _executing = executing;
188 | [self didChangeValueForKey:@"isExecuting"];
189 | }
190 |
191 | - (BOOL)isConcurrent {
192 | return YES;
193 | }
194 |
195 | #pragma mark NSURLConnection (delegate)
196 |
197 | - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
198 | if (![response respondsToSelector:@selector(statusCode)] || [((NSHTTPURLResponse *)response) statusCode] < 400) {
199 | NSInteger expected = response.expectedContentLength > 0 ? (NSInteger)response.expectedContentLength : 0;
200 | self.expectedSize = expected;
201 | if (self.progressBlock) {
202 | self.progressBlock(0, expected);
203 | }
204 |
205 | self.imageData = [[NSMutableData alloc] initWithCapacity:expected];
206 | }
207 | else {
208 | [self.connection cancel];
209 |
210 | [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil];
211 |
212 | if (self.completedBlock) {
213 | self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:[((NSHTTPURLResponse *)response) statusCode] userInfo:nil], YES);
214 | }
215 | CFRunLoopStop(CFRunLoopGetCurrent());
216 | [self done];
217 | }
218 | }
219 |
220 | - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
221 | [self.imageData appendData:data];
222 |
223 | if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0 && self.completedBlock) {
224 | // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/
225 | // Thanks to the author @Nyx0uf
226 |
227 | // Get the total bytes downloaded
228 | const NSInteger totalSize = self.imageData.length;
229 |
230 | // Update the data source, we must pass ALL the data, not just the new bytes
231 | CGImageSourceRef imageSource = CGImageSourceCreateIncremental(NULL);
232 | CGImageSourceUpdateData(imageSource, (__bridge CFDataRef)self.imageData, totalSize == self.expectedSize);
233 |
234 | if (width + height == 0) {
235 | CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL);
236 | if (properties) {
237 | NSInteger orientationValue = -1;
238 | CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight);
239 | if (val) CFNumberGetValue(val, kCFNumberLongType, &height);
240 | val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth);
241 | if (val) CFNumberGetValue(val, kCFNumberLongType, &width);
242 | val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation);
243 | if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue);
244 | CFRelease(properties);
245 |
246 | // When we draw to Core Graphics, we lose orientation information,
247 | // which means the image below born of initWithCGIImage will be
248 | // oriented incorrectly sometimes. (Unlike the image born of initWithData
249 | // in connectionDidFinishLoading.) So save it here and pass it on later.
250 | orientation = [[self class] orientationFromPropertyValue:(orientationValue == -1 ? 1 : orientationValue)];
251 | }
252 |
253 | }
254 |
255 | if (width + height > 0 && totalSize < self.expectedSize) {
256 | // Create the image
257 | CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
258 |
259 | #ifdef TARGET_OS_IPHONE
260 | // Workaround for iOS anamorphic image
261 | if (partialImageRef) {
262 | const size_t partialHeight = CGImageGetHeight(partialImageRef);
263 | CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
264 | CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
265 | CGColorSpaceRelease(colorSpace);
266 | if (bmContext) {
267 | CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = partialHeight}, partialImageRef);
268 | CGImageRelease(partialImageRef);
269 | partialImageRef = CGBitmapContextCreateImage(bmContext);
270 | CGContextRelease(bmContext);
271 | }
272 | else {
273 | CGImageRelease(partialImageRef);
274 | partialImageRef = nil;
275 | }
276 | }
277 | #endif
278 |
279 | if (partialImageRef) {
280 | UIImage *image = [UIImage imageWithCGImage:partialImageRef scale:1 orientation:orientation];
281 | NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL];
282 | UIImage *scaledImage = [self scaledImageForKey:key image:image];
283 | image = [UIImage decodedImageWithImage:scaledImage];
284 | CGImageRelease(partialImageRef);
285 | dispatch_main_sync_safe(^{
286 | if (self.completedBlock) {
287 | self.completedBlock(image, nil, nil, NO);
288 | }
289 | });
290 | }
291 | }
292 |
293 | CFRelease(imageSource);
294 | }
295 |
296 | if (self.progressBlock) {
297 | self.progressBlock(self.imageData.length, self.expectedSize);
298 | }
299 | }
300 |
301 | + (UIImageOrientation)orientationFromPropertyValue:(NSInteger)value {
302 | switch (value) {
303 | case 1:
304 | return UIImageOrientationUp;
305 | case 3:
306 | return UIImageOrientationDown;
307 | case 8:
308 | return UIImageOrientationLeft;
309 | case 6:
310 | return UIImageOrientationRight;
311 | case 2:
312 | return UIImageOrientationUpMirrored;
313 | case 4:
314 | return UIImageOrientationDownMirrored;
315 | case 5:
316 | return UIImageOrientationLeftMirrored;
317 | case 7:
318 | return UIImageOrientationRightMirrored;
319 | default:
320 | return UIImageOrientationUp;
321 | }
322 | }
323 |
324 | - (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image {
325 | return SDScaledImageForKey(key, image);
326 | }
327 |
328 | - (void)connectionDidFinishLoading:(NSURLConnection *)aConnection {
329 | SDWebImageDownloaderCompletedBlock completionBlock = self.completedBlock;
330 | @synchronized(self) {
331 | CFRunLoopStop(CFRunLoopGetCurrent());
332 | self.thread = nil;
333 | self.connection = nil;
334 | [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil];
335 | }
336 |
337 | if (![[NSURLCache sharedURLCache] cachedResponseForRequest:_request]) {
338 | responseFromCached = NO;
339 | }
340 |
341 | if (completionBlock)
342 | {
343 | if (self.options & SDWebImageDownloaderIgnoreCachedResponse && responseFromCached) {
344 | completionBlock(nil, nil, nil, YES);
345 | }
346 | else {
347 | UIImage *image = [UIImage sd_imageWithData:self.imageData];
348 | NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL];
349 | image = [self scaledImageForKey:key image:image];
350 |
351 | // Do not force decoding animated GIFs
352 | if (!image.images) {
353 | image = [UIImage decodedImageWithImage:image];
354 | }
355 | if (CGSizeEqualToSize(image.size, CGSizeZero)) {
356 | completionBlock(nil, nil, [NSError errorWithDomain:@"SDWebImageErrorDomain" code:0 userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image has 0 pixels"}], YES);
357 | }
358 | else {
359 | completionBlock(image, self.imageData, nil, YES);
360 | }
361 | }
362 | }
363 | self.completionBlock = nil;
364 | [self done];
365 | }
366 |
367 | - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
368 | CFRunLoopStop(CFRunLoopGetCurrent());
369 | [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil];
370 |
371 | if (self.completedBlock) {
372 | self.completedBlock(nil, nil, error, YES);
373 | }
374 |
375 | [self done];
376 | }
377 |
378 | - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
379 | responseFromCached = NO; // If this method is called, it means the response wasn't read from cache
380 | if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData) {
381 | // Prevents caching of responses
382 | return nil;
383 | }
384 | else {
385 | return cachedResponse;
386 | }
387 | }
388 |
389 | - (BOOL)shouldContinueWhenAppEntersBackground {
390 | return self.options & SDWebImageDownloaderContinueInBackground;
391 | }
392 |
393 | - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection {
394 | return self.shouldUseCredentialStorage;
395 | }
396 |
397 | - (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
398 | if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
399 | NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
400 | [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
401 | } else {
402 | if ([challenge previousFailureCount] == 0) {
403 | if (self.credential) {
404 | [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge];
405 | } else {
406 | [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
407 | }
408 | } else {
409 | [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
410 | }
411 | }
412 | }
413 |
414 | @end
415 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/SDWebImageManager.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import "SDWebImageCompat.h"
10 | #import "SDWebImageOperation.h"
11 | #import "SDWebImageDownloader.h"
12 | #import "SDImageCache.h"
13 |
14 | typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) {
15 | /**
16 | * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying.
17 | * This flag disable this blacklisting.
18 | */
19 | SDWebImageRetryFailed = 1 << 0,
20 |
21 | /**
22 | * By default, image downloads are started during UI interactions, this flags disable this feature,
23 | * leading to delayed download on UIScrollView deceleration for instance.
24 | */
25 | SDWebImageLowPriority = 1 << 1,
26 |
27 | /**
28 | * This flag disables on-disk caching
29 | */
30 | SDWebImageCacheMemoryOnly = 1 << 2,
31 |
32 | /**
33 | * This flag enables progressive download, the image is displayed progressively during download as a browser would do.
34 | * By default, the image is only displayed once completely downloaded.
35 | */
36 | SDWebImageProgressiveDownload = 1 << 3,
37 |
38 | /**
39 | * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed.
40 | * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation.
41 | * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics.
42 | * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image.
43 | *
44 | * Use this flag only if you can't make your URLs static with embeded cache busting parameter.
45 | */
46 | SDWebImageRefreshCached = 1 << 4,
47 |
48 | /**
49 | * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for
50 | * extra time in background to let the request finish. If the background task expires the operation will be cancelled.
51 | */
52 | SDWebImageContinueInBackground = 1 << 5,
53 |
54 | /**
55 | * Handles cookies stored in NSHTTPCookieStore by setting
56 | * NSMutableURLRequest.HTTPShouldHandleCookies = YES;
57 | */
58 | SDWebImageHandleCookies = 1 << 6,
59 |
60 | /**
61 | * Enable to allow untrusted SSL ceriticates.
62 | * Useful for testing purposes. Use with caution in production.
63 | */
64 | SDWebImageAllowInvalidSSLCertificates = 1 << 7,
65 |
66 | /**
67 | * By default, image are loaded in the order they were queued. This flag move them to
68 | * the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which
69 | * could take a while).
70 | */
71 | SDWebImageHighPriority = 1 << 8,
72 |
73 | /**
74 | * By default, placeholder images are loaded while the image is loading. This flag will delay the loading
75 | * of the placeholder image until after the image has finished loading.
76 | */
77 | SDWebImageDelayPlaceholder = 1 << 9
78 | };
79 |
80 | typedef void(^SDWebImageCompletionBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL);
81 |
82 | typedef void(^SDWebImageCompletionWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL);
83 |
84 | typedef NSString *(^SDWebImageCacheKeyFilterBlock)(NSURL *url);
85 |
86 |
87 | @class SDWebImageManager;
88 |
89 | @protocol SDWebImageManagerDelegate
90 |
91 | @optional
92 |
93 | /**
94 | * Controls which image should be downloaded when the image is not found in the cache.
95 | *
96 | * @param imageManager The current `SDWebImageManager`
97 | * @param imageURL The url of the image to be downloaded
98 | *
99 | * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied.
100 | */
101 | - (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL;
102 |
103 | /**
104 | * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory.
105 | * NOTE: This method is called from a global queue in order to not to block the main thread.
106 | *
107 | * @param imageManager The current `SDWebImageManager`
108 | * @param image The image to transform
109 | * @param imageURL The url of the image to transform
110 | *
111 | * @return The transformed image object.
112 | */
113 | - (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL;
114 |
115 | @end
116 |
117 | /**
118 | * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes.
119 | * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache).
120 | * You can use this class directly to benefit from web image downloading with caching in another context than
121 | * a UIView.
122 | *
123 | * Here is a simple example of how to use SDWebImageManager:
124 | *
125 | * @code
126 |
127 | SDWebImageManager *manager = [SDWebImageManager sharedManager];
128 | [manager downloadWithURL:imageURL
129 | options:0
130 | progress:nil
131 | completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
132 | if (image) {
133 | // do something with image
134 | }
135 | }];
136 |
137 | * @endcode
138 | */
139 | @interface SDWebImageManager : NSObject
140 |
141 | @property (weak, nonatomic) id delegate;
142 |
143 | @property (strong, nonatomic, readonly) SDImageCache *imageCache;
144 | @property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader;
145 |
146 | /**
147 | * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can
148 | * be used to remove dynamic part of an image URL.
149 | *
150 | * The following example sets a filter in the application delegate that will remove any query-string from the
151 | * URL before to use it as a cache key:
152 | *
153 | * @code
154 |
155 | [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) {
156 | url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path];
157 | return [url absoluteString];
158 | }];
159 |
160 | * @endcode
161 | */
162 | @property (copy) SDWebImageCacheKeyFilterBlock cacheKeyFilter;
163 |
164 | /**
165 | * Returns global SDWebImageManager instance.
166 | *
167 | * @return SDWebImageManager shared instance
168 | */
169 | + (SDWebImageManager *)sharedManager;
170 |
171 | /**
172 | * Downloads the image at the given URL if not present in cache or return the cached version otherwise.
173 | *
174 | * @param url The URL to the image
175 | * @param options A mask to specify options to use for this request
176 | * @param progressBlock A block called while image is downloading
177 | * @param completedBlock A block called when operation has been completed.
178 | *
179 | * This parameter is required.
180 | *
181 | * This block has no return value and takes the requested UIImage as first parameter.
182 | * In case of error the image parameter is nil and the second parameter may contain an NSError.
183 | *
184 | * The third parameter is an `SDImageCacheType` enum indicating if the image was retrived from the local cache
185 | * or from the memory cache or from the network.
186 | *
187 | * The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is
188 | * downloading. This block is thus called repetidly with a partial image. When image is fully downloaded, the
189 | * block is called a last time with the full image and the last parameter set to YES.
190 | *
191 | * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation
192 | */
193 | - (id )downloadImageWithURL:(NSURL *)url
194 | options:(SDWebImageOptions)options
195 | progress:(SDWebImageDownloaderProgressBlock)progressBlock
196 | completed:(SDWebImageCompletionWithFinishedBlock)completedBlock;
197 |
198 | /**
199 | * Saves image to cache for given URL
200 | *
201 | * @param image The image to cache
202 | * @param url The URL to the image
203 | *
204 | */
205 |
206 | - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url;
207 |
208 | /**
209 | * Cancel all current opreations
210 | */
211 | - (void)cancelAll;
212 |
213 | /**
214 | * Check one or more operations running
215 | */
216 | - (BOOL)isRunning;
217 |
218 | /**
219 | * Check if image has already been cached
220 | *
221 | * @param url image url
222 | *
223 | * @return if the image was already cached
224 | */
225 | - (BOOL)cachedImageExistsForURL:(NSURL *)url;
226 |
227 | /**
228 | * Check if image has already been cached on disk only
229 | *
230 | * @param url image url
231 | *
232 | * @return if the image was already cached (disk only)
233 | */
234 | - (BOOL)diskImageExistsForURL:(NSURL *)url;
235 |
236 | /**
237 | * Async check if image has already been cached
238 | *
239 | * @param url image url
240 | * @param completionBlock the block to be executed when the check is finished
241 | *
242 | * @note the completion block is always executed on the main queue
243 | */
244 | - (void)cachedImageExistsForURL:(NSURL *)url
245 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;
246 |
247 | /**
248 | * Async check if image has already been cached on disk only
249 | *
250 | * @param url image url
251 | * @param completionBlock the block to be executed when the check is finished
252 | *
253 | * @note the completion block is always executed on the main queue
254 | */
255 | - (void)diskImageExistsForURL:(NSURL *)url
256 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;
257 |
258 |
259 | /**
260 | *Return the cache key for a given URL
261 | */
262 | - (NSString *)cacheKeyForURL:(NSURL *)url;
263 |
264 | @end
265 |
266 |
267 | #pragma mark - Deprecated
268 |
269 | typedef void(^SDWebImageCompletedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionBlock`");
270 | typedef void(^SDWebImageCompletedWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionWithFinishedBlock`");
271 |
272 |
273 | @interface SDWebImageManager (Deprecated)
274 |
275 | /**
276 | * Downloads the image at the given URL if not present in cache or return the cached version otherwise.
277 | *
278 | * @deprecated This method has been deprecated. Use `downloadImageWithURL:options:progress:completed:`
279 | */
280 | - (id )downloadWithURL:(NSURL *)url
281 | options:(SDWebImageOptions)options
282 | progress:(SDWebImageDownloaderProgressBlock)progressBlock
283 | completed:(SDWebImageCompletedWithFinishedBlock)completedBlock __deprecated_msg("Method deprecated. Use `downloadImageWithURL:options:progress:completed:`");
284 |
285 | @end
286 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/SDWebImageManager.m:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import "SDWebImageManager.h"
10 | #import
11 |
12 | @interface SDWebImageCombinedOperation : NSObject
13 |
14 | @property (assign, nonatomic, getter = isCancelled) BOOL cancelled;
15 | @property (copy, nonatomic) SDWebImageNoParamsBlock cancelBlock;
16 | @property (strong, nonatomic) NSOperation *cacheOperation;
17 |
18 | @end
19 |
20 | @interface SDWebImageManager ()
21 |
22 | @property (strong, nonatomic, readwrite) SDImageCache *imageCache;
23 | @property (strong, nonatomic, readwrite) SDWebImageDownloader *imageDownloader;
24 | @property (strong, nonatomic) NSMutableArray *failedURLs;
25 | @property (strong, nonatomic) NSMutableArray *runningOperations;
26 |
27 | @end
28 |
29 | @implementation SDWebImageManager
30 |
31 | + (id)sharedManager {
32 | static dispatch_once_t once;
33 | static id instance;
34 | dispatch_once(&once, ^{
35 | instance = [self new];
36 | });
37 | return instance;
38 | }
39 |
40 | - (id)init {
41 | if ((self = [super init])) {
42 | _imageCache = [self createCache];
43 | _imageDownloader = [SDWebImageDownloader sharedDownloader];
44 | _failedURLs = [NSMutableArray new];
45 | _runningOperations = [NSMutableArray new];
46 | }
47 | return self;
48 | }
49 |
50 | - (SDImageCache *)createCache {
51 | return [SDImageCache sharedImageCache];
52 | }
53 |
54 | - (NSString *)cacheKeyForURL:(NSURL *)url {
55 | if (self.cacheKeyFilter) {
56 | return self.cacheKeyFilter(url);
57 | }
58 | else {
59 | return [url absoluteString];
60 | }
61 | }
62 |
63 | - (BOOL)cachedImageExistsForURL:(NSURL *)url {
64 | NSString *key = [self cacheKeyForURL:url];
65 | if ([self.imageCache imageFromMemoryCacheForKey:key] != nil) return YES;
66 | return [self.imageCache diskImageExistsWithKey:key];
67 | }
68 |
69 | - (BOOL)diskImageExistsForURL:(NSURL *)url {
70 | NSString *key = [self cacheKeyForURL:url];
71 | return [self.imageCache diskImageExistsWithKey:key];
72 | }
73 |
74 | - (void)cachedImageExistsForURL:(NSURL *)url
75 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock {
76 | NSString *key = [self cacheKeyForURL:url];
77 |
78 | BOOL isInMemoryCache = ([self.imageCache imageFromMemoryCacheForKey:key] != nil);
79 |
80 | if (isInMemoryCache) {
81 | // making sure we call the completion block on the main queue
82 | dispatch_async(dispatch_get_main_queue(), ^{
83 | if (completionBlock) {
84 | completionBlock(YES);
85 | }
86 | });
87 | return;
88 | }
89 |
90 | [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
91 | // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
92 | if (completionBlock) {
93 | completionBlock(isInDiskCache);
94 | }
95 | }];
96 | }
97 |
98 | - (void)diskImageExistsForURL:(NSURL *)url
99 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock {
100 | NSString *key = [self cacheKeyForURL:url];
101 |
102 | [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
103 | // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
104 | if (completionBlock) {
105 | completionBlock(isInDiskCache);
106 | }
107 | }];
108 | }
109 |
110 | - (id )downloadImageWithURL:(NSURL *)url
111 | options:(SDWebImageOptions)options
112 | progress:(SDWebImageDownloaderProgressBlock)progressBlock
113 | completed:(SDWebImageCompletionWithFinishedBlock)completedBlock {
114 | // Invoking this method without a completedBlock is pointless
115 | NSParameterAssert(completedBlock);
116 |
117 | // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, XCode won't
118 | // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString.
119 | if ([url isKindOfClass:NSString.class]) {
120 | url = [NSURL URLWithString:(NSString *)url];
121 | }
122 |
123 | // Prevents app crashing on argument type error like sending NSNull instead of NSURL
124 | if (![url isKindOfClass:NSURL.class]) {
125 | url = nil;
126 | }
127 |
128 | __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];
129 | __weak SDWebImageCombinedOperation *weakOperation = operation;
130 |
131 | BOOL isFailedUrl = NO;
132 | @synchronized (self.failedURLs) {
133 | isFailedUrl = [self.failedURLs containsObject:url];
134 | }
135 |
136 | if (!url || (!(options & SDWebImageRetryFailed) && isFailedUrl)) {
137 | dispatch_main_sync_safe(^{
138 | NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil];
139 | completedBlock(nil, error, SDImageCacheTypeNone, YES, url);
140 | });
141 | return operation;
142 | }
143 |
144 | @synchronized (self.runningOperations) {
145 | [self.runningOperations addObject:operation];
146 | }
147 | NSString *key = [self cacheKeyForURL:url];
148 |
149 | operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) {
150 | if (operation.isCancelled) {
151 | @synchronized (self.runningOperations) {
152 | [self.runningOperations removeObject:operation];
153 | }
154 |
155 | return;
156 | }
157 |
158 | if ((!image || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) {
159 | if (image && options & SDWebImageRefreshCached) {
160 | dispatch_main_sync_safe(^{
161 | // If image was found in the cache bug SDWebImageRefreshCached is provided, notify about the cached image
162 | // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server.
163 | completedBlock(image, nil, cacheType, YES, url);
164 | });
165 | }
166 |
167 | // download if no image or requested to refresh anyway, and download allowed by delegate
168 | SDWebImageDownloaderOptions downloaderOptions = 0;
169 | if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority;
170 | if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload;
171 | if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache;
172 | if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground;
173 | if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies;
174 | if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates;
175 | if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority;
176 | if (image && options & SDWebImageRefreshCached) {
177 | // force progressive off if image already cached but forced refreshing
178 | downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload;
179 | // ignore image read from NSURLCache if image if cached but force refreshing
180 | downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse;
181 | }
182 | id subOperation = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *data, NSError *error, BOOL finished) {
183 | if (weakOperation.isCancelled) {
184 | // Do nothing if the operation was cancelled
185 | // See #699 for more details
186 | // if we would call the completedBlock, there could be a race condition between this block and another completedBlock for the same object, so if this one is called second, we will overwrite the new data
187 | }
188 | else if (error) {
189 | dispatch_main_sync_safe(^{
190 | if (!weakOperation.isCancelled) {
191 | completedBlock(nil, error, SDImageCacheTypeNone, finished, url);
192 | }
193 | });
194 |
195 | if (error.code != NSURLErrorNotConnectedToInternet && error.code != NSURLErrorCancelled && error.code != NSURLErrorTimedOut) {
196 | @synchronized (self.failedURLs) {
197 | [self.failedURLs addObject:url];
198 | }
199 | }
200 | }
201 | else {
202 | BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly);
203 |
204 | if (options & SDWebImageRefreshCached && image && !downloadedImage) {
205 | // Image refresh hit the NSURLCache cache, do not call the completion block
206 | }
207 | // NOTE: We don't call transformDownloadedImage delegate method on animated images as most transformation code would mangle it
208 | else if (downloadedImage && !downloadedImage.images && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) {
209 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
210 | UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url];
211 |
212 | if (transformedImage && finished) {
213 | BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage];
214 | [self.imageCache storeImage:transformedImage recalculateFromImage:imageWasTransformed imageData:data forKey:key toDisk:cacheOnDisk];
215 | }
216 |
217 | dispatch_main_sync_safe(^{
218 | if (!weakOperation.isCancelled) {
219 | completedBlock(transformedImage, nil, SDImageCacheTypeNone, finished, url);
220 | }
221 | });
222 | });
223 | }
224 | else {
225 | if (downloadedImage && finished) {
226 | [self.imageCache storeImage:downloadedImage recalculateFromImage:NO imageData:data forKey:key toDisk:cacheOnDisk];
227 | }
228 |
229 | dispatch_main_sync_safe(^{
230 | if (!weakOperation.isCancelled) {
231 | completedBlock(downloadedImage, nil, SDImageCacheTypeNone, finished, url);
232 | }
233 | });
234 | }
235 | }
236 |
237 | if (finished) {
238 | @synchronized (self.runningOperations) {
239 | [self.runningOperations removeObject:operation];
240 | }
241 | }
242 | }];
243 | operation.cancelBlock = ^{
244 | [subOperation cancel];
245 |
246 | @synchronized (self.runningOperations) {
247 | [self.runningOperations removeObject:weakOperation];
248 | }
249 | };
250 | }
251 | else if (image) {
252 | dispatch_main_sync_safe(^{
253 | if (!weakOperation.isCancelled) {
254 | completedBlock(image, nil, cacheType, YES, url);
255 | }
256 | });
257 | @synchronized (self.runningOperations) {
258 | [self.runningOperations removeObject:operation];
259 | }
260 | }
261 | else {
262 | // Image not in cache and download disallowed by delegate
263 | dispatch_main_sync_safe(^{
264 | if (!weakOperation.isCancelled) {
265 | completedBlock(nil, nil, SDImageCacheTypeNone, YES, url);
266 | }
267 | });
268 | @synchronized (self.runningOperations) {
269 | [self.runningOperations removeObject:operation];
270 | }
271 | }
272 | }];
273 |
274 | return operation;
275 | }
276 |
277 | - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url {
278 | if (image && url) {
279 | NSString *key = [self cacheKeyForURL:url];
280 | [self.imageCache storeImage:image forKey:key toDisk:YES];
281 | }
282 | }
283 |
284 | - (void)cancelAll {
285 | @synchronized (self.runningOperations) {
286 | [self.runningOperations makeObjectsPerformSelector:@selector(cancel)];
287 | [self.runningOperations removeAllObjects];
288 | }
289 | }
290 |
291 | - (BOOL)isRunning {
292 | return self.runningOperations.count > 0;
293 | }
294 |
295 | @end
296 |
297 |
298 | @implementation SDWebImageCombinedOperation
299 |
300 | - (void)setCancelBlock:(SDWebImageNoParamsBlock)cancelBlock {
301 | // check if the operation is already cancelled, then we just call the cancelBlock
302 | if (self.isCancelled) {
303 | if (cancelBlock) {
304 | cancelBlock();
305 | }
306 | _cancelBlock = nil; // don't forget to nil the cancelBlock, otherwise we will get crashes
307 | } else {
308 | _cancelBlock = [cancelBlock copy];
309 | }
310 | }
311 |
312 | - (void)cancel {
313 | self.cancelled = YES;
314 | if (self.cacheOperation) {
315 | [self.cacheOperation cancel];
316 | self.cacheOperation = nil;
317 | }
318 | if (self.cancelBlock) {
319 | self.cancelBlock();
320 |
321 | // TODO: this is a temporary fix to #809.
322 | // Until we can figure the exact cause of the crash, going with the ivar instead of the setter
323 | // self.cancelBlock = nil;
324 | _cancelBlock = nil;
325 | }
326 | }
327 |
328 | @end
329 |
330 |
331 | @implementation SDWebImageManager (Deprecated)
332 |
333 | // deprecated method, uses the non deprecated method
334 | // adapter for the completion block
335 | - (id )downloadWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedWithFinishedBlock)completedBlock {
336 | return [self downloadImageWithURL:url
337 | options:options
338 | progress:progressBlock
339 | completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
340 | if (completedBlock) {
341 | completedBlock(image, error, cacheType, finished);
342 | }
343 | }];
344 | }
345 |
346 | @end
347 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/SDWebImageOperation.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import
10 |
11 | @protocol SDWebImageOperation
12 |
13 | - (void)cancel;
14 |
15 | @end
16 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/SDWebImagePrefetcher.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import
10 | #import "SDWebImageManager.h"
11 |
12 | @class SDWebImagePrefetcher;
13 |
14 | @protocol SDWebImagePrefetcherDelegate
15 |
16 | @optional
17 |
18 | /**
19 | * Called when an image was prefetched.
20 | *
21 | * @param imagePrefetcher The current image prefetcher
22 | * @param imageURL The image url that was prefetched
23 | * @param finishedCount The total number of images that were prefetched (successful or not)
24 | * @param totalCount The total number of images that were to be prefetched
25 | */
26 | - (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount;
27 |
28 | /**
29 | * Called when all images are prefetched.
30 | * @param imagePrefetcher The current image prefetcher
31 | * @param totalCount The total number of images that were prefetched (whether successful or not)
32 | * @param skippedCount The total number of images that were skipped
33 | */
34 | - (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount;
35 |
36 | @end
37 |
38 | typedef void(^SDWebImagePrefetcherProgressBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls);
39 | typedef void(^SDWebImagePrefetcherCompletionBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfSkippedUrls);
40 |
41 | /**
42 | * Prefetch some URLs in the cache for future use. Images are downloaded in low priority.
43 | */
44 | @interface SDWebImagePrefetcher : NSObject
45 |
46 | /**
47 | * The web image manager
48 | */
49 | @property (strong, nonatomic, readonly) SDWebImageManager *manager;
50 |
51 | /**
52 | * Maximum number of URLs to prefetch at the same time. Defaults to 3.
53 | */
54 | @property (nonatomic, assign) NSUInteger maxConcurrentDownloads;
55 |
56 | /**
57 | * SDWebImageOptions for prefetcher. Defaults to SDWebImageLowPriority.
58 | */
59 | @property (nonatomic, assign) SDWebImageOptions options;
60 |
61 | @property (weak, nonatomic) id delegate;
62 |
63 | /**
64 | * Return the global image prefetcher instance.
65 | */
66 | + (SDWebImagePrefetcher *)sharedImagePrefetcher;
67 |
68 | /**
69 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching,
70 | * currently one image is downloaded at a time,
71 | * and skips images for failed downloads and proceed to the next image in the list
72 | *
73 | * @param urls list of URLs to prefetch
74 | */
75 | - (void)prefetchURLs:(NSArray *)urls;
76 |
77 | /**
78 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching,
79 | * currently one image is downloaded at a time,
80 | * and skips images for failed downloads and proceed to the next image in the list
81 | *
82 | * @param urls list of URLs to prefetch
83 | * @param progressBlock block to be called when progress updates;
84 | * first parameter is the number of completed (successful or not) requests,
85 | * second parameter is the total number of images originally requested to be prefetched
86 | * @param completionBlock block to be called when prefetching is completed
87 | * first param is the number of completed (successful or not) requests,
88 | * second parameter is the number of skipped requests
89 | */
90 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock;
91 |
92 | /**
93 | * Remove and cancel queued list
94 | */
95 | - (void)cancelPrefetching;
96 |
97 |
98 | @end
99 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/SDWebImagePrefetcher.m:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import "SDWebImagePrefetcher.h"
10 |
11 | #if !defined(DEBUG) && !defined (SD_VERBOSE)
12 | #define NSLog(...)
13 | #endif
14 |
15 | @interface SDWebImagePrefetcher ()
16 |
17 | @property (strong, nonatomic) SDWebImageManager *manager;
18 | @property (strong, nonatomic) NSArray *prefetchURLs;
19 | @property (assign, nonatomic) NSUInteger requestedCount;
20 | @property (assign, nonatomic) NSUInteger skippedCount;
21 | @property (assign, nonatomic) NSUInteger finishedCount;
22 | @property (assign, nonatomic) NSTimeInterval startedTime;
23 | @property (copy, nonatomic) SDWebImagePrefetcherCompletionBlock completionBlock;
24 | @property (copy, nonatomic) SDWebImagePrefetcherProgressBlock progressBlock;
25 |
26 | @end
27 |
28 | @implementation SDWebImagePrefetcher
29 |
30 | + (SDWebImagePrefetcher *)sharedImagePrefetcher {
31 | static dispatch_once_t once;
32 | static id instance;
33 | dispatch_once(&once, ^{
34 | instance = [self new];
35 | });
36 | return instance;
37 | }
38 |
39 | - (id)init {
40 | if ((self = [super init])) {
41 | _manager = [SDWebImageManager new];
42 | _options = SDWebImageLowPriority;
43 | self.maxConcurrentDownloads = 3;
44 | }
45 | return self;
46 | }
47 |
48 | - (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads {
49 | self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads;
50 | }
51 |
52 | - (NSUInteger)maxConcurrentDownloads {
53 | return self.manager.imageDownloader.maxConcurrentDownloads;
54 | }
55 |
56 | - (void)startPrefetchingAtIndex:(NSUInteger)index {
57 | if (index >= self.prefetchURLs.count) return;
58 | self.requestedCount++;
59 | [self.manager downloadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
60 | if (!finished) return;
61 | self.finishedCount++;
62 |
63 | if (image) {
64 | if (self.progressBlock) {
65 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]);
66 | }
67 | NSLog(@"Prefetched %@ out of %@", @(self.finishedCount), @(self.prefetchURLs.count));
68 | }
69 | else {
70 | if (self.progressBlock) {
71 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]);
72 | }
73 | NSLog(@"Prefetched %@ out of %@ (Failed)", @(self.finishedCount), @(self.prefetchURLs.count));
74 |
75 | // Add last failed
76 | self.skippedCount++;
77 | }
78 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) {
79 | [self.delegate imagePrefetcher:self
80 | didPrefetchURL:self.prefetchURLs[index]
81 | finishedCount:self.finishedCount
82 | totalCount:self.prefetchURLs.count
83 | ];
84 | }
85 |
86 | if (self.prefetchURLs.count > self.requestedCount) {
87 | dispatch_async(dispatch_get_main_queue(), ^{
88 | [self startPrefetchingAtIndex:self.requestedCount];
89 | });
90 | }
91 | else if (self.finishedCount == self.requestedCount) {
92 | [self reportStatus];
93 | if (self.completionBlock) {
94 | self.completionBlock(self.finishedCount, self.skippedCount);
95 | self.completionBlock = nil;
96 | }
97 | }
98 | }];
99 | }
100 |
101 | - (void)reportStatus {
102 | NSUInteger total = [self.prefetchURLs count];
103 | NSLog(@"Finished prefetching (%@ successful, %@ skipped, timeElasped %.2f)", @(total - self.skippedCount), @(self.skippedCount), CFAbsoluteTimeGetCurrent() - self.startedTime);
104 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) {
105 | [self.delegate imagePrefetcher:self
106 | didFinishWithTotalCount:(total - self.skippedCount)
107 | skippedCount:self.skippedCount
108 | ];
109 | }
110 | }
111 |
112 | - (void)prefetchURLs:(NSArray *)urls {
113 | [self prefetchURLs:urls progress:nil completed:nil];
114 | }
115 |
116 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock {
117 | [self cancelPrefetching]; // Prevent duplicate prefetch request
118 | self.startedTime = CFAbsoluteTimeGetCurrent();
119 | self.prefetchURLs = urls;
120 | self.completionBlock = completionBlock;
121 | self.progressBlock = progressBlock;
122 |
123 | // Starts prefetching from the very first image on the list with the max allowed concurrency
124 | NSUInteger listCount = self.prefetchURLs.count;
125 | for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) {
126 | [self startPrefetchingAtIndex:i];
127 | }
128 | }
129 |
130 | - (void)cancelPrefetching {
131 | self.prefetchURLs = nil;
132 | self.skippedCount = 0;
133 | self.requestedCount = 0;
134 | self.finishedCount = 0;
135 | [self.manager cancelAll];
136 | }
137 |
138 | @end
139 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/UIButton+WebCache.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import "SDWebImageCompat.h"
10 | #import "SDWebImageManager.h"
11 |
12 | /**
13 | * Integrates SDWebImage async downloading and caching of remote images with UIButtonView.
14 | */
15 | @interface UIButton (WebCache)
16 |
17 | /**
18 | * Get the current image URL.
19 | */
20 | - (NSURL *)sd_currentImageURL;
21 |
22 | /**
23 | * Get the image URL for a control state.
24 | *
25 | * @param state Which state you want to know the URL for. The values are described in UIControlState.
26 | */
27 | - (NSURL *)sd_imageURLForState:(UIControlState)state;
28 |
29 | /**
30 | * Set the imageView `image` with an `url`.
31 | *
32 | * The download is asynchronous and cached.
33 | *
34 | * @param url The url for the image.
35 | * @param state The state that uses the specified title. The values are described in UIControlState.
36 | */
37 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state;
38 |
39 | /**
40 | * Set the imageView `image` with an `url` and a placeholder.
41 | *
42 | * The download is asynchronous and cached.
43 | *
44 | * @param url The url for the image.
45 | * @param state The state that uses the specified title. The values are described in UIControlState.
46 | * @param placeholder The image to be set initially, until the image request finishes.
47 | * @see sd_setImageWithURL:placeholderImage:options:
48 | */
49 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder;
50 |
51 | /**
52 | * Set the imageView `image` with an `url`, placeholder and custom options.
53 | *
54 | * The download is asynchronous and cached.
55 | *
56 | * @param url The url for the image.
57 | * @param state The state that uses the specified title. The values are described in UIControlState.
58 | * @param placeholder The image to be set initially, until the image request finishes.
59 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
60 | */
61 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
62 |
63 | /**
64 | * Set the imageView `image` with an `url`.
65 | *
66 | * The download is asynchronous and cached.
67 | *
68 | * @param url The url for the image.
69 | * @param state The state that uses the specified title. The values are described in UIControlState.
70 | * @param completedBlock A block called when operation has been completed. This block has no return value
71 | * and takes the requested UIImage as first parameter. In case of error the image parameter
72 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
73 | * indicating if the image was retrived from the local cache of from the network.
74 | * The forth parameter is the original image url.
75 | */
76 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock;
77 |
78 | /**
79 | * Set the imageView `image` with an `url`, placeholder.
80 | *
81 | * The download is asynchronous and cached.
82 | *
83 | * @param url The url for the image.
84 | * @param state The state that uses the specified title. The values are described in UIControlState.
85 | * @param placeholder The image to be set initially, until the image request finishes.
86 | * @param completedBlock A block called when operation has been completed. This block has no return value
87 | * and takes the requested UIImage as first parameter. In case of error the image parameter
88 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
89 | * indicating if the image was retrived from the local cache of from the network.
90 | * The forth parameter is the original image url.
91 | */
92 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;
93 |
94 | /**
95 | * Set the imageView `image` with an `url`, placeholder and custom options.
96 | *
97 | * The download is asynchronous and cached.
98 | *
99 | * @param url The url for the image.
100 | * @param state The state that uses the specified title. The values are described in UIControlState.
101 | * @param placeholder The image to be set initially, until the image request finishes.
102 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
103 | * @param completedBlock A block called when operation has been completed. This block has no return value
104 | * and takes the requested UIImage as first parameter. In case of error the image parameter
105 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
106 | * indicating if the image was retrived from the local cache of from the network.
107 | * The forth parameter is the original image url.
108 | */
109 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
110 |
111 | /**
112 | * Set the backgroundImageView `image` with an `url`.
113 | *
114 | * The download is asynchronous and cached.
115 | *
116 | * @param url The url for the image.
117 | * @param state The state that uses the specified title. The values are described in UIControlState.
118 | */
119 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state;
120 |
121 | /**
122 | * Set the backgroundImageView `image` with an `url` and a placeholder.
123 | *
124 | * The download is asynchronous and cached.
125 | *
126 | * @param url The url for the image.
127 | * @param state The state that uses the specified title. The values are described in UIControlState.
128 | * @param placeholder The image to be set initially, until the image request finishes.
129 | * @see sd_setImageWithURL:placeholderImage:options:
130 | */
131 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder;
132 |
133 | /**
134 | * Set the backgroundImageView `image` with an `url`, placeholder and custom options.
135 | *
136 | * The download is asynchronous and cached.
137 | *
138 | * @param url The url for the image.
139 | * @param state The state that uses the specified title. The values are described in UIControlState.
140 | * @param placeholder The image to be set initially, until the image request finishes.
141 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
142 | */
143 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
144 |
145 | /**
146 | * Set the backgroundImageView `image` with an `url`.
147 | *
148 | * The download is asynchronous and cached.
149 | *
150 | * @param url The url for the image.
151 | * @param state The state that uses the specified title. The values are described in UIControlState.
152 | * @param completedBlock A block called when operation has been completed. This block has no return value
153 | * and takes the requested UIImage as first parameter. In case of error the image parameter
154 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
155 | * indicating if the image was retrived from the local cache of from the network.
156 | * The forth parameter is the original image url.
157 | */
158 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock;
159 |
160 | /**
161 | * Set the backgroundImageView `image` with an `url`, placeholder.
162 | *
163 | * The download is asynchronous and cached.
164 | *
165 | * @param url The url for the image.
166 | * @param state The state that uses the specified title. The values are described in UIControlState.
167 | * @param placeholder The image to be set initially, until the image request finishes.
168 | * @param completedBlock A block called when operation has been completed. This block has no return value
169 | * and takes the requested UIImage as first parameter. In case of error the image parameter
170 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
171 | * indicating if the image was retrived from the local cache of from the network.
172 | * The forth parameter is the original image url.
173 | */
174 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;
175 |
176 | /**
177 | * Set the backgroundImageView `image` with an `url`, placeholder and custom options.
178 | *
179 | * The download is asynchronous and cached.
180 | *
181 | * @param url The url for the image.
182 | * @param placeholder The image to be set initially, until the image request finishes.
183 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
184 | * @param completedBlock A block called when operation has been completed. This block has no return value
185 | * and takes the requested UIImage as first parameter. In case of error the image parameter
186 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
187 | * indicating if the image was retrived from the local cache of from the network.
188 | * The forth parameter is the original image url.
189 | */
190 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
191 |
192 | /**
193 | * Cancel the current image download
194 | */
195 | - (void)sd_cancelImageLoadForState:(UIControlState)state;
196 |
197 | /**
198 | * Cancel the current backgroundImage download
199 | */
200 | - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state;
201 |
202 | @end
203 |
204 |
205 | @interface UIButton (WebCacheDeprecated)
206 |
207 | - (NSURL *)currentImageURL __deprecated_msg("Use `sd_currentImageURL`");
208 | - (NSURL *)imageURLForState:(UIControlState)state __deprecated_msg("Use `sd_imageURLForState:`");
209 |
210 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:`");
211 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:`");
212 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:options:`");
213 |
214 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:completed:`");
215 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:completed:`");
216 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:options:completed:`");
217 |
218 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:`");
219 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:`");
220 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:options:`");
221 |
222 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:completed:`");
223 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:completed:`");
224 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:options:completed:`");
225 |
226 | - (void)cancelCurrentImageLoad __deprecated_msg("Use `sd_cancelImageLoadForState:`");
227 | - (void)cancelBackgroundImageLoadForState:(UIControlState)state __deprecated_msg("Use `sd_cancelBackgroundImageLoadForState:`");
228 |
229 | @end
230 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/UIButton+WebCache.m:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import "UIButton+WebCache.h"
10 | #import "objc/runtime.h"
11 | #import "UIView+WebCacheOperation.h"
12 |
13 | static char imageURLStorageKey;
14 |
15 | @implementation UIButton (WebCache)
16 |
17 | - (NSURL *)sd_currentImageURL {
18 | NSURL *url = self.imageURLStorage[@(self.state)];
19 |
20 | if (!url) {
21 | url = self.imageURLStorage[@(UIControlStateNormal)];
22 | }
23 |
24 | return url;
25 | }
26 |
27 | - (NSURL *)sd_imageURLForState:(UIControlState)state {
28 | return self.imageURLStorage[@(state)];
29 | }
30 |
31 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state {
32 | [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
33 | }
34 |
35 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder {
36 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
37 | }
38 |
39 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
40 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil];
41 | }
42 |
43 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock {
44 | [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock];
45 | }
46 |
47 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock {
48 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock];
49 | }
50 |
51 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
52 |
53 | [self setImage:placeholder forState:state];
54 | [self sd_cancelImageLoadForState:state];
55 |
56 | if (!url) {
57 | [self.imageURLStorage removeObjectForKey:@(state)];
58 |
59 | dispatch_main_async_safe(^{
60 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
61 | if (completedBlock) {
62 | completedBlock(nil, error, SDImageCacheTypeNone, url);
63 | }
64 | });
65 |
66 | return;
67 | }
68 |
69 | self.imageURLStorage[@(state)] = url;
70 |
71 | __weak UIButton *wself = self;
72 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
73 | if (!wself) return;
74 | dispatch_main_sync_safe(^{
75 | __strong UIButton *sself = wself;
76 | if (!sself) return;
77 | if (image) {
78 | [sself setImage:image forState:state];
79 | }
80 | if (completedBlock && finished) {
81 | completedBlock(image, error, cacheType, url);
82 | }
83 | });
84 | }];
85 | [self sd_setImageLoadOperation:operation forState:state];
86 | }
87 |
88 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state {
89 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
90 | }
91 |
92 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder {
93 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
94 | }
95 |
96 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
97 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil];
98 | }
99 |
100 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock {
101 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock];
102 | }
103 |
104 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock {
105 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock];
106 | }
107 |
108 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
109 | [self sd_cancelImageLoadForState:state];
110 |
111 | [self setBackgroundImage:placeholder forState:state];
112 |
113 | if (url) {
114 | __weak UIButton *wself = self;
115 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
116 | if (!wself) return;
117 | dispatch_main_sync_safe(^{
118 | __strong UIButton *sself = wself;
119 | if (!sself) return;
120 | if (image) {
121 | [sself setBackgroundImage:image forState:state];
122 | }
123 | if (completedBlock && finished) {
124 | completedBlock(image, error, cacheType, url);
125 | }
126 | });
127 | }];
128 | [self sd_setBackgroundImageLoadOperation:operation forState:state];
129 | } else {
130 | dispatch_main_async_safe(^{
131 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
132 | if (completedBlock) {
133 | completedBlock(nil, error, SDImageCacheTypeNone, url);
134 | }
135 | });
136 | }
137 | }
138 |
139 | - (void)sd_setImageLoadOperation:(id)operation forState:(UIControlState)state {
140 | [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]];
141 | }
142 |
143 | - (void)sd_cancelImageLoadForState:(UIControlState)state {
144 | [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]];
145 | }
146 |
147 | - (void)sd_setBackgroundImageLoadOperation:(id)operation forState:(UIControlState)state {
148 | [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]];
149 | }
150 |
151 | - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state {
152 | [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]];
153 | }
154 |
155 | - (NSMutableDictionary *)imageURLStorage {
156 | NSMutableDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey);
157 | if (!storage)
158 | {
159 | storage = [NSMutableDictionary dictionary];
160 | objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
161 | }
162 |
163 | return storage;
164 | }
165 |
166 | @end
167 |
168 |
169 | @implementation UIButton (WebCacheDeprecated)
170 |
171 | - (NSURL *)currentImageURL {
172 | return [self sd_currentImageURL];
173 | }
174 |
175 | - (NSURL *)imageURLForState:(UIControlState)state {
176 | return [self sd_imageURLForState:state];
177 | }
178 |
179 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state {
180 | [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
181 | }
182 |
183 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder {
184 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
185 | }
186 |
187 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
188 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil];
189 | }
190 |
191 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock {
192 | [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
193 | if (completedBlock) {
194 | completedBlock(image, error, cacheType);
195 | }
196 | }];
197 | }
198 |
199 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock {
200 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
201 | if (completedBlock) {
202 | completedBlock(image, error, cacheType);
203 | }
204 | }];
205 | }
206 |
207 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock {
208 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
209 | if (completedBlock) {
210 | completedBlock(image, error, cacheType);
211 | }
212 | }];
213 | }
214 |
215 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state {
216 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
217 | }
218 |
219 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder {
220 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
221 | }
222 |
223 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
224 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil];
225 | }
226 |
227 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock {
228 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
229 | if (completedBlock) {
230 | completedBlock(image, error, cacheType);
231 | }
232 | }];
233 | }
234 |
235 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock {
236 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
237 | if (completedBlock) {
238 | completedBlock(image, error, cacheType);
239 | }
240 | }];
241 | }
242 |
243 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock {
244 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
245 | if (completedBlock) {
246 | completedBlock(image, error, cacheType);
247 | }
248 | }];
249 | }
250 |
251 | - (void)cancelCurrentImageLoad {
252 | // in a backwards compatible manner, cancel for current state
253 | [self sd_cancelImageLoadForState:self.state];
254 | }
255 |
256 | - (void)cancelBackgroundImageLoadForState:(UIControlState)state {
257 | [self sd_cancelBackgroundImageLoadForState:state];
258 | }
259 |
260 | @end
261 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/UIImage+GIF.h:
--------------------------------------------------------------------------------
1 | //
2 | // UIImage+GIF.h
3 | // LBGIFImage
4 | //
5 | // Created by Laurin Brandner on 06.01.12.
6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface UIImage (GIF)
12 |
13 | + (UIImage *)sd_animatedGIFNamed:(NSString *)name;
14 |
15 | + (UIImage *)sd_animatedGIFWithData:(NSData *)data;
16 |
17 | - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size;
18 |
19 | @end
20 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/UIImage+GIF.m:
--------------------------------------------------------------------------------
1 | //
2 | // UIImage+GIF.m
3 | // LBGIFImage
4 | //
5 | // Created by Laurin Brandner on 06.01.12.
6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved.
7 | //
8 |
9 | #import "UIImage+GIF.h"
10 | #import
11 |
12 | @implementation UIImage (GIF)
13 |
14 | + (UIImage *)sd_animatedGIFWithData:(NSData *)data {
15 | if (!data) {
16 | return nil;
17 | }
18 |
19 | CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
20 |
21 | size_t count = CGImageSourceGetCount(source);
22 |
23 | UIImage *animatedImage;
24 |
25 | if (count <= 1) {
26 | animatedImage = [[UIImage alloc] initWithData:data];
27 | }
28 | else {
29 | NSMutableArray *images = [NSMutableArray array];
30 |
31 | NSTimeInterval duration = 0.0f;
32 |
33 | for (size_t i = 0; i < count; i++) {
34 | CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
35 |
36 | duration += [self sd_frameDurationAtIndex:i source:source];
37 |
38 | [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
39 |
40 | CGImageRelease(image);
41 | }
42 |
43 | if (!duration) {
44 | duration = (1.0f / 10.0f) * count;
45 | }
46 |
47 | animatedImage = [UIImage animatedImageWithImages:images duration:duration];
48 | }
49 |
50 | CFRelease(source);
51 |
52 | return animatedImage;
53 | }
54 |
55 | + (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
56 | float frameDuration = 0.1f;
57 | CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
58 | NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties;
59 | NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];
60 |
61 | NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
62 | if (delayTimeUnclampedProp) {
63 | frameDuration = [delayTimeUnclampedProp floatValue];
64 | }
65 | else {
66 |
67 | NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
68 | if (delayTimeProp) {
69 | frameDuration = [delayTimeProp floatValue];
70 | }
71 | }
72 |
73 | // Many annoying ads specify a 0 duration to make an image flash as quickly as possible.
74 | // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify
75 | // a duration of <= 10 ms. See and
76 | // for more information.
77 |
78 | if (frameDuration < 0.011f) {
79 | frameDuration = 0.100f;
80 | }
81 |
82 | CFRelease(cfFrameProperties);
83 | return frameDuration;
84 | }
85 |
86 | + (UIImage *)sd_animatedGIFNamed:(NSString *)name {
87 | CGFloat scale = [UIScreen mainScreen].scale;
88 |
89 | if (scale > 1.0f) {
90 | NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"];
91 |
92 | NSData *data = [NSData dataWithContentsOfFile:retinaPath];
93 |
94 | if (data) {
95 | return [UIImage sd_animatedGIFWithData:data];
96 | }
97 |
98 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
99 |
100 | data = [NSData dataWithContentsOfFile:path];
101 |
102 | if (data) {
103 | return [UIImage sd_animatedGIFWithData:data];
104 | }
105 |
106 | return [UIImage imageNamed:name];
107 | }
108 | else {
109 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
110 |
111 | NSData *data = [NSData dataWithContentsOfFile:path];
112 |
113 | if (data) {
114 | return [UIImage sd_animatedGIFWithData:data];
115 | }
116 |
117 | return [UIImage imageNamed:name];
118 | }
119 | }
120 |
121 | - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size {
122 | if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) {
123 | return self;
124 | }
125 |
126 | CGSize scaledSize = size;
127 | CGPoint thumbnailPoint = CGPointZero;
128 |
129 | CGFloat widthFactor = size.width / self.size.width;
130 | CGFloat heightFactor = size.height / self.size.height;
131 | CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor;
132 | scaledSize.width = self.size.width * scaleFactor;
133 | scaledSize.height = self.size.height * scaleFactor;
134 |
135 | if (widthFactor > heightFactor) {
136 | thumbnailPoint.y = (size.height - scaledSize.height) * 0.5;
137 | }
138 | else if (widthFactor < heightFactor) {
139 | thumbnailPoint.x = (size.width - scaledSize.width) * 0.5;
140 | }
141 |
142 | NSMutableArray *scaledImages = [NSMutableArray array];
143 |
144 | UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
145 |
146 | for (UIImage *image in self.images) {
147 | [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)];
148 | UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
149 |
150 | [scaledImages addObject:newImage];
151 | }
152 |
153 | UIGraphicsEndImageContext();
154 |
155 | return [UIImage animatedImageWithImages:scaledImages duration:self.duration];
156 | }
157 |
158 | @end
159 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/UIImage+MultiFormat.h:
--------------------------------------------------------------------------------
1 | //
2 | // UIImage+MultiFormat.h
3 | // SDWebImage
4 | //
5 | // Created by Olivier Poitrey on 07/06/13.
6 | // Copyright (c) 2013 Dailymotion. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface UIImage (MultiFormat)
12 |
13 | + (UIImage *)sd_imageWithData:(NSData *)data;
14 |
15 | @end
16 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/UIImage+MultiFormat.m:
--------------------------------------------------------------------------------
1 | //
2 | // UIImage+MultiFormat.m
3 | // SDWebImage
4 | //
5 | // Created by Olivier Poitrey on 07/06/13.
6 | // Copyright (c) 2013 Dailymotion. All rights reserved.
7 | //
8 |
9 | #import "UIImage+MultiFormat.h"
10 | #import "UIImage+GIF.h"
11 | #import "NSData+ImageContentType.h"
12 | #import
13 |
14 | #ifdef SD_WEBP
15 | #import "UIImage+WebP.h"
16 | #endif
17 |
18 | @implementation UIImage (MultiFormat)
19 |
20 | + (UIImage *)sd_imageWithData:(NSData *)data {
21 | UIImage *image;
22 | NSString *imageContentType = [NSData sd_contentTypeForImageData:data];
23 | if ([imageContentType isEqualToString:@"image/gif"]) {
24 | image = [UIImage sd_animatedGIFWithData:data];
25 | }
26 | #ifdef SD_WEBP
27 | else if ([imageContentType isEqualToString:@"image/webp"])
28 | {
29 | image = [UIImage sd_imageWithWebPData:data];
30 | }
31 | #endif
32 | else {
33 | image = [[UIImage alloc] initWithData:data];
34 | UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data];
35 | if (orientation != UIImageOrientationUp) {
36 | image = [UIImage imageWithCGImage:image.CGImage
37 | scale:image.scale
38 | orientation:orientation];
39 | }
40 | }
41 |
42 |
43 | return image;
44 | }
45 |
46 |
47 | +(UIImageOrientation)sd_imageOrientationFromImageData:(NSData *)imageData {
48 | UIImageOrientation result = UIImageOrientationUp;
49 | CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL);
50 | if (imageSource) {
51 | CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL);
52 | if (properties) {
53 | CFTypeRef val;
54 | int exifOrientation;
55 | val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation);
56 | if (val) {
57 | CFNumberGetValue(val, kCFNumberIntType, &exifOrientation);
58 | result = [self sd_exifOrientationToiOSOrientation:exifOrientation];
59 | } // else - if it's not set it remains at up
60 | CFRelease((CFTypeRef) properties);
61 | } else {
62 | //NSLog(@"NO PROPERTIES, FAIL");
63 | }
64 | CFRelease(imageSource);
65 | }
66 | return result;
67 | }
68 |
69 | #pragma mark EXIF orientation tag converter
70 | // Convert an EXIF image orientation to an iOS one.
71 | // reference see here: http://sylvana.net/jpegcrop/exif_orientation.html
72 | + (UIImageOrientation) sd_exifOrientationToiOSOrientation:(int)exifOrientation {
73 | UIImageOrientation orientation = UIImageOrientationUp;
74 | switch (exifOrientation) {
75 | case 1:
76 | orientation = UIImageOrientationUp;
77 | break;
78 |
79 | case 3:
80 | orientation = UIImageOrientationDown;
81 | break;
82 |
83 | case 8:
84 | orientation = UIImageOrientationLeft;
85 | break;
86 |
87 | case 6:
88 | orientation = UIImageOrientationRight;
89 | break;
90 |
91 | case 2:
92 | orientation = UIImageOrientationUpMirrored;
93 | break;
94 |
95 | case 4:
96 | orientation = UIImageOrientationDownMirrored;
97 | break;
98 |
99 | case 5:
100 | orientation = UIImageOrientationLeftMirrored;
101 | break;
102 |
103 | case 7:
104 | orientation = UIImageOrientationRightMirrored;
105 | break;
106 | default:
107 | break;
108 | }
109 | return orientation;
110 | }
111 |
112 |
113 |
114 | @end
115 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/UIImageView+HighlightedWebCache.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import
10 | #import "SDWebImageCompat.h"
11 | #import "SDWebImageManager.h"
12 |
13 | /**
14 | * Integrates SDWebImage async downloading and caching of remote images with UIImageView for highlighted state.
15 | */
16 | @interface UIImageView (HighlightedWebCache)
17 |
18 | /**
19 | * Set the imageView `highlightedImage` with an `url`.
20 | *
21 | * The download is asynchronous and cached.
22 | *
23 | * @param url The url for the image.
24 | */
25 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url;
26 |
27 | /**
28 | * Set the imageView `highlightedImage` with an `url` and custom options.
29 | *
30 | * The download is asynchronous and cached.
31 | *
32 | * @param url The url for the image.
33 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
34 | */
35 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options;
36 |
37 | /**
38 | * Set the imageView `highlightedImage` with an `url`.
39 | *
40 | * The download is asynchronous and cached.
41 | *
42 | * @param url The url for the image.
43 | * @param completedBlock A block called when operation has been completed. This block has no return value
44 | * and takes the requested UIImage as first parameter. In case of error the image parameter
45 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
46 | * indicating if the image was retrived from the local cache of from the network.
47 | * The forth parameter is the original image url.
48 | */
49 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock;
50 |
51 | /**
52 | * Set the imageView `highlightedImage` with an `url` and custom options.
53 | *
54 | * The download is asynchronous and cached.
55 | *
56 | * @param url The url for the image.
57 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
58 | * @param completedBlock A block called when operation has been completed. This block has no return value
59 | * and takes the requested UIImage as first parameter. In case of error the image parameter
60 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
61 | * indicating if the image was retrived from the local cache of from the network.
62 | * The forth parameter is the original image url.
63 | */
64 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
65 |
66 | /**
67 | * Set the imageView `highlightedImage` with an `url` and custom options.
68 | *
69 | * The download is asynchronous and cached.
70 | *
71 | * @param url The url for the image.
72 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
73 | * @param progressBlock A block called while image is downloading
74 | * @param completedBlock A block called when operation has been completed. This block has no return value
75 | * and takes the requested UIImage as first parameter. In case of error the image parameter
76 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
77 | * indicating if the image was retrived from the local cache of from the network.
78 | * The forth parameter is the original image url.
79 | */
80 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;
81 |
82 | /**
83 | * Cancel the current download
84 | */
85 | - (void)sd_cancelCurrentHighlightedImageLoad;
86 |
87 | @end
88 |
89 |
90 | @interface UIImageView (HighlightedWebCacheDeprecated)
91 |
92 | - (void)setHighlightedImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:`");
93 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:`");
94 | - (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:completed:`");
95 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:completed:`");
96 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:progress:completed:`");
97 |
98 | - (void)cancelCurrentHighlightedImageLoad __deprecated_msg("Use `sd_cancelCurrentHighlightedImageLoad`");
99 |
100 | @end
101 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/UIImageView+HighlightedWebCache.m:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import "UIImageView+HighlightedWebCache.h"
10 | #import "UIView+WebCacheOperation.h"
11 |
12 | #define UIImageViewHighlightedWebCacheOperationKey @"highlightedImage"
13 |
14 | @implementation UIImageView (HighlightedWebCache)
15 |
16 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url {
17 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil];
18 | }
19 |
20 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options {
21 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil];
22 | }
23 |
24 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock {
25 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:completedBlock];
26 | }
27 |
28 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
29 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:completedBlock];
30 | }
31 |
32 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
33 | [self sd_cancelCurrentHighlightedImageLoad];
34 |
35 | if (url) {
36 | __weak UIImageView *wself = self;
37 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
38 | if (!wself) return;
39 | dispatch_main_sync_safe (^
40 | {
41 | if (!wself) return;
42 | if (image) {
43 | wself.highlightedImage = image;
44 | [wself setNeedsLayout];
45 | }
46 | if (completedBlock && finished) {
47 | completedBlock(image, error, cacheType, url);
48 | }
49 | });
50 | }];
51 | [self sd_setImageLoadOperation:operation forKey:UIImageViewHighlightedWebCacheOperationKey];
52 | } else {
53 | dispatch_main_async_safe(^{
54 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
55 | if (completedBlock) {
56 | completedBlock(nil, error, SDImageCacheTypeNone, url);
57 | }
58 | });
59 | }
60 | }
61 |
62 | - (void)sd_cancelCurrentHighlightedImageLoad {
63 | [self sd_cancelImageLoadOperationWithKey:UIImageViewHighlightedWebCacheOperationKey];
64 | }
65 |
66 | @end
67 |
68 |
69 | @implementation UIImageView (HighlightedWebCacheDeprecated)
70 |
71 | - (void)setHighlightedImageWithURL:(NSURL *)url {
72 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil];
73 | }
74 |
75 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options {
76 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil];
77 | }
78 |
79 | - (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock {
80 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
81 | if (completedBlock) {
82 | completedBlock(image, error, cacheType);
83 | }
84 | }];
85 | }
86 |
87 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock {
88 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
89 | if (completedBlock) {
90 | completedBlock(image, error, cacheType);
91 | }
92 | }];
93 | }
94 |
95 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock {
96 | [self sd_setHighlightedImageWithURL:url options:0 progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
97 | if (completedBlock) {
98 | completedBlock(image, error, cacheType);
99 | }
100 | }];
101 | }
102 |
103 | - (void)cancelCurrentHighlightedImageLoad {
104 | [self sd_cancelCurrentHighlightedImageLoad];
105 | }
106 |
107 | @end
108 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/UIImageView+WebCache.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import "SDWebImageCompat.h"
10 | #import "SDWebImageManager.h"
11 |
12 | /**
13 | * Integrates SDWebImage async downloading and caching of remote images with UIImageView.
14 | *
15 | * Usage with a UITableViewCell sub-class:
16 | *
17 | * @code
18 |
19 | #import
20 |
21 | ...
22 |
23 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
24 | {
25 | static NSString *MyIdentifier = @"MyIdentifier";
26 |
27 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
28 |
29 | if (cell == nil) {
30 | cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier]
31 | autorelease];
32 | }
33 |
34 | // Here we use the provided sd_setImageWithURL: method to load the web image
35 | // Ensure you use a placeholder image otherwise cells will be initialized with no image
36 | [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"]
37 | placeholderImage:[UIImage imageNamed:@"placeholder"]];
38 |
39 | cell.textLabel.text = @"My Text";
40 | return cell;
41 | }
42 |
43 | * @endcode
44 | */
45 | @interface UIImageView (WebCache)
46 |
47 | /**
48 | * Get the current image URL.
49 | *
50 | * Note that because of the limitations of categories this property can get out of sync
51 | * if you use sd_setImage: directly.
52 | */
53 | - (NSURL *)sd_imageURL;
54 |
55 | /**
56 | * Set the imageView `image` with an `url`.
57 | *
58 | * The download is asynchronous and cached.
59 | *
60 | * @param url The url for the image.
61 | */
62 | - (void)sd_setImageWithURL:(NSURL *)url;
63 |
64 | /**
65 | * Set the imageView `image` with an `url` and a placeholder.
66 | *
67 | * The download is asynchronous and cached.
68 | *
69 | * @param url The url for the image.
70 | * @param placeholder The image to be set initially, until the image request finishes.
71 | * @see sd_setImageWithURL:placeholderImage:options:
72 | */
73 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder;
74 |
75 | /**
76 | * Set the imageView `image` with an `url`, placeholder and custom options.
77 | *
78 | * The download is asynchronous and cached.
79 | *
80 | * @param url The url for the image.
81 | * @param placeholder The image to be set initially, until the image request finishes.
82 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
83 | */
84 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
85 |
86 | /**
87 | * Set the imageView `image` with an `url`.
88 | *
89 | * The download is asynchronous and cached.
90 | *
91 | * @param url The url for the image.
92 | * @param completedBlock A block called when operation has been completed. This block has no return value
93 | * and takes the requested UIImage as first parameter. In case of error the image parameter
94 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
95 | * indicating if the image was retrived from the local cache of from the network.
96 | * The forth parameter is the original image url.
97 | */
98 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock;
99 |
100 | /**
101 | * Set the imageView `image` with an `url`, placeholder.
102 | *
103 | * The download is asynchronous and cached.
104 | *
105 | * @param url The url for the image.
106 | * @param placeholder The image to be set initially, until the image request finishes.
107 | * @param completedBlock A block called when operation has been completed. This block has no return value
108 | * and takes the requested UIImage as first parameter. In case of error the image parameter
109 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
110 | * indicating if the image was retrived from the local cache of from the network.
111 | * The forth parameter is the original image url.
112 | */
113 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;
114 |
115 | /**
116 | * Set the imageView `image` with an `url`, placeholder and custom options.
117 | *
118 | * The download is asynchronous and cached.
119 | *
120 | * @param url The url for the image.
121 | * @param placeholder The image to be set initially, until the image request finishes.
122 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
123 | * @param completedBlock A block called when operation has been completed. This block has no return value
124 | * and takes the requested UIImage as first parameter. In case of error the image parameter
125 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
126 | * indicating if the image was retrived from the local cache of from the network.
127 | * The forth parameter is the original image url.
128 | */
129 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
130 |
131 | /**
132 | * Set the imageView `image` with an `url`, placeholder and custom options.
133 | *
134 | * The download is asynchronous and cached.
135 | *
136 | * @param url The url for the image.
137 | * @param placeholder The image to be set initially, until the image request finishes.
138 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
139 | * @param progressBlock A block called while image is downloading
140 | * @param completedBlock A block called when operation has been completed. This block has no return value
141 | * and takes the requested UIImage as first parameter. In case of error the image parameter
142 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
143 | * indicating if the image was retrived from the local cache of from the network.
144 | * The forth parameter is the original image url.
145 | */
146 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;
147 |
148 | /**
149 | * Set the imageView `image` with an `url` and a optionaly placeholder image.
150 | *
151 | * The download is asynchronous and cached.
152 | *
153 | * @param url The url for the image.
154 | * @param placeholder The image to be set initially, until the image request finishes.
155 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
156 | * @param progressBlock A block called while image is downloading
157 | * @param completedBlock A block called when operation has been completed. This block has no return value
158 | * and takes the requested UIImage as first parameter. In case of error the image parameter
159 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean
160 | * indicating if the image was retrived from the local cache of from the network.
161 | * The forth parameter is the original image url.
162 | */
163 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;
164 |
165 | /**
166 | * Download an array of images and starts them in an animation loop
167 | *
168 | * @param arrayOfURLs An array of NSURL
169 | */
170 | - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs;
171 |
172 | /**
173 | * Cancel the current download
174 | */
175 | - (void)sd_cancelCurrentImageLoad;
176 |
177 | - (void)sd_cancelCurrentAnimationImagesLoad;
178 |
179 | @end
180 |
181 |
182 | @interface UIImageView (WebCacheDeprecated)
183 |
184 | - (NSURL *)imageURL __deprecated_msg("Use `sd_imageURL`");
185 |
186 | - (void)setImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:`");
187 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:`");
188 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options`");
189 |
190 | - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:completed:`");
191 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:completed:`");
192 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:completed:`");
193 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:progress:completed:`");
194 |
195 | - (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs __deprecated_msg("Use `sd_setAnimationImagesWithURLs:`");
196 |
197 | - (void)cancelCurrentArrayLoad __deprecated_msg("Use `sd_cancelCurrentAnimationImagesLoad`");
198 |
199 | - (void)cancelCurrentImageLoad __deprecated_msg("Use `sd_cancelCurrentImageLoad`");
200 |
201 | @end
202 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/UIImageView+WebCache.m:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import "UIImageView+WebCache.h"
10 | #import "objc/runtime.h"
11 | #import "UIView+WebCacheOperation.h"
12 |
13 | static char imageURLKey;
14 |
15 | @implementation UIImageView (WebCache)
16 |
17 | - (void)sd_setImageWithURL:(NSURL *)url {
18 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil];
19 | }
20 |
21 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder {
22 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil];
23 | }
24 |
25 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
26 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil];
27 | }
28 |
29 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock {
30 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock];
31 | }
32 |
33 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock {
34 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock];
35 | }
36 |
37 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
38 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock];
39 | }
40 |
41 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
42 | [self sd_cancelCurrentImageLoad];
43 | objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
44 |
45 | if (!(options & SDWebImageDelayPlaceholder)) {
46 | self.image = placeholder;
47 | }
48 |
49 | if (url) {
50 | __weak UIImageView *wself = self;
51 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
52 | if (!wself) return;
53 | dispatch_main_sync_safe(^{
54 | if (!wself) return;
55 | if (image) {
56 | wself.image = image;
57 | [wself setNeedsLayout];
58 | } else {
59 | if ((options & SDWebImageDelayPlaceholder)) {
60 | wself.image = placeholder;
61 | [wself setNeedsLayout];
62 | }
63 | }
64 | if (completedBlock && finished) {
65 | completedBlock(image, error, cacheType, url);
66 | }
67 | });
68 | }];
69 | [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"];
70 | } else {
71 | dispatch_main_async_safe(^{
72 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
73 | if (completedBlock) {
74 | completedBlock(nil, error, SDImageCacheTypeNone, url);
75 | }
76 | });
77 | }
78 | }
79 |
80 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
81 | NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url];
82 | UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key];
83 |
84 | [self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock];
85 | }
86 |
87 | - (NSURL *)sd_imageURL {
88 | return objc_getAssociatedObject(self, &imageURLKey);
89 | }
90 |
91 | - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs {
92 | [self sd_cancelCurrentAnimationImagesLoad];
93 | __weak UIImageView *wself = self;
94 |
95 | NSMutableArray *operationsArray = [[NSMutableArray alloc] init];
96 |
97 | for (NSURL *logoImageURL in arrayOfURLs) {
98 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
99 | if (!wself) return;
100 | dispatch_main_sync_safe(^{
101 | __strong UIImageView *sself = wself;
102 | [sself stopAnimating];
103 | if (sself && image) {
104 | NSMutableArray *currentImages = [[sself animationImages] mutableCopy];
105 | if (!currentImages) {
106 | currentImages = [[NSMutableArray alloc] init];
107 | }
108 | [currentImages addObject:image];
109 |
110 | sself.animationImages = currentImages;
111 | [sself setNeedsLayout];
112 | }
113 | [sself startAnimating];
114 | });
115 | }];
116 | [operationsArray addObject:operation];
117 | }
118 |
119 | [self sd_setImageLoadOperation:[NSArray arrayWithArray:operationsArray] forKey:@"UIImageViewAnimationImages"];
120 | }
121 |
122 | - (void)sd_cancelCurrentImageLoad {
123 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"];
124 | }
125 |
126 | - (void)sd_cancelCurrentAnimationImagesLoad {
127 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"];
128 | }
129 |
130 | @end
131 |
132 |
133 | @implementation UIImageView (WebCacheDeprecated)
134 |
135 | - (NSURL *)imageURL {
136 | return [self sd_imageURL];
137 | }
138 |
139 | - (void)setImageWithURL:(NSURL *)url {
140 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil];
141 | }
142 |
143 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder {
144 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil];
145 | }
146 |
147 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
148 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil];
149 | }
150 |
151 | - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock {
152 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
153 | if (completedBlock) {
154 | completedBlock(image, error, cacheType);
155 | }
156 | }];
157 | }
158 |
159 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock {
160 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
161 | if (completedBlock) {
162 | completedBlock(image, error, cacheType);
163 | }
164 | }];
165 | }
166 |
167 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock {
168 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
169 | if (completedBlock) {
170 | completedBlock(image, error, cacheType);
171 | }
172 | }];
173 | }
174 |
175 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock {
176 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
177 | if (completedBlock) {
178 | completedBlock(image, error, cacheType);
179 | }
180 | }];
181 | }
182 |
183 | - (void)cancelCurrentArrayLoad {
184 | [self sd_cancelCurrentAnimationImagesLoad];
185 | }
186 |
187 | - (void)cancelCurrentImageLoad {
188 | [self sd_cancelCurrentImageLoad];
189 | }
190 |
191 | - (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs {
192 | [self sd_setAnimationImagesWithURLs:arrayOfURLs];
193 | }
194 |
195 | @end
196 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/UIView+WebCacheOperation.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import
10 | #import "SDWebImageManager.h"
11 |
12 | @interface UIView (WebCacheOperation)
13 |
14 | /**
15 | * Set the image load operation (storage in a UIView based dictionary)
16 | *
17 | * @param operation the operation
18 | * @param key key for storing the operation
19 | */
20 | - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key;
21 |
22 | /**
23 | * Cancel all operations for the current UIView and key
24 | *
25 | * @param key key for identifying the operations
26 | */
27 | - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key;
28 |
29 | /**
30 | * Just remove the operations corresponding to the current UIView and key without cancelling them
31 | *
32 | * @param key key for identifying the operations
33 | */
34 | - (void)sd_removeImageLoadOperationWithKey:(NSString *)key;
35 |
36 | @end
37 |
--------------------------------------------------------------------------------
/WaveLoadingView/SDWebImage/UIView+WebCacheOperation.m:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the SDWebImage package.
3 | * (c) Olivier Poitrey
4 | *
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | #import "UIView+WebCacheOperation.h"
10 | #import "objc/runtime.h"
11 |
12 | static char loadOperationKey;
13 |
14 | @implementation UIView (WebCacheOperation)
15 |
16 | - (NSMutableDictionary *)operationDictionary {
17 | NSMutableDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey);
18 | if (operations) {
19 | return operations;
20 | }
21 | operations = [NSMutableDictionary dictionary];
22 | objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
23 | return operations;
24 | }
25 |
26 | - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key {
27 | [self sd_cancelImageLoadOperationWithKey:key];
28 | NSMutableDictionary *operationDictionary = [self operationDictionary];
29 | [operationDictionary setObject:operation forKey:key];
30 | }
31 |
32 | - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key {
33 | // Cancel in progress downloader from queue
34 | NSMutableDictionary *operationDictionary = [self operationDictionary];
35 | id operations = [operationDictionary objectForKey:key];
36 | if (operations) {
37 | if ([operations isKindOfClass:[NSArray class]]) {
38 | for (id operation in operations) {
39 | if (operation) {
40 | [operation cancel];
41 | }
42 | }
43 | } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){
44 | [(id) operations cancel];
45 | }
46 | [operationDictionary removeObjectForKey:key];
47 | }
48 | }
49 |
50 | - (void)sd_removeImageLoadOperationWithKey:(NSString *)key {
51 | NSMutableDictionary *operationDictionary = [self operationDictionary];
52 | [operationDictionary removeObjectForKey:key];
53 | }
54 |
55 | @end
56 |
--------------------------------------------------------------------------------
/WaveLoadingView/ViewController.swift:
--------------------------------------------------------------------------------
1 | //
2 | // ViewController.swift
3 | // WaveLoadingView
4 | //
5 | // Created by lzy on 15/12/30.
6 | // Copyright © 2015年 lzy. All rights reserved.
7 | //
8 |
9 | import UIKit
10 |
11 | class ViewController: UIViewController {
12 |
13 |
14 | @IBOutlet weak var waveLoadingIndicator: WaveLoadingIndicator!
15 | @IBOutlet weak var progressSliderBar: UISlider!
16 | @IBOutlet weak var amplitudeSliderBar: UISlider!
17 | @IBOutlet weak var borderWidthSliderBar: UISlider!
18 |
19 | @IBOutlet weak var isShowTipButton: UIButton!
20 | @IBOutlet weak var changeShapeButton: UIButton!
21 | @IBOutlet weak var exampleButton: UIButton!
22 |
23 |
24 | override func viewDidLoad() {
25 | super.viewDidLoad()
26 |
27 | radiusButton()
28 |
29 | waveLoadingIndicator.isShowProgressText = false
30 |
31 | self.navigationController?.navigationBar.translucent = false
32 | self.navigationController?.navigationBar.shadowImage = UIImage(named: "shadow")
33 | }
34 |
35 |
36 | @IBAction func clickIsShowTipButton(sender: UIButton) {
37 | waveLoadingIndicator.isShowProgressText = !waveLoadingIndicator.isShowProgressText
38 | }
39 |
40 | @IBAction func clickChangeShapeButton(sender: UIButton) {
41 | waveLoadingIndicator.shapeModel = (waveLoadingIndicator.shapeModel == ShapeModel.shapeModelCircle) ? ShapeModel.shapeModelRect : ShapeModel.shapeModelCircle
42 | }
43 |
44 | @IBAction func sliderBarValueDidChanged(sender: AnyObject) {
45 | if sender.tag == 10 {
46 | self.performSelector("setWaveValue:", withObject: progressSliderBar.value, afterDelay: 0.3)
47 | } else if sender.tag == 11 {
48 | waveLoadingIndicator.waveAmplitude = WaveLoadingIndicator.amplitudeMin + Double(amplitudeSliderBar.value) * WaveLoadingIndicator.amplitudeSpan
49 | } else if sender.tag == 12 {
50 | waveLoadingIndicator.borderWidth = CGFloat(1) + CGFloat(3 * borderWidthSliderBar.value)
51 | }
52 | }
53 |
54 | @IBAction func clickExampleButton(sender: AnyObject) {
55 | let exampleController = DisplayViewController()
56 | self.navigationController?.pushViewController(exampleController, animated: true)
57 | }
58 |
59 |
60 | func setWaveValue(value: AnyObject) {
61 | waveLoadingIndicator.progress = value.doubleValue
62 | }
63 |
64 | func radiusButton() {
65 | isShowTipButton.layer.cornerRadius = isShowTipButton.bounds.size.height/2
66 | isShowTipButton.layer.masksToBounds = true
67 | changeShapeButton.layer.cornerRadius = changeShapeButton.bounds.size.height/2
68 | changeShapeButton.layer.masksToBounds = true
69 | exampleButton.layer.cornerRadius = exampleButton.bounds.size.height/2
70 | exampleButton.layer.masksToBounds = true
71 |
72 | }
73 |
74 | override func didReceiveMemoryWarning() {
75 | super.didReceiveMemoryWarning()
76 | // Dispose of any resources that can be recreated.
77 | }
78 |
79 |
80 | }
81 |
82 |
--------------------------------------------------------------------------------
/WaveLoadingView/WaveloadingView-Bridging-Header.h:
--------------------------------------------------------------------------------
1 |
2 |
3 | #import "UIImageView+WebCache.h"
--------------------------------------------------------------------------------
/WaveLoadingView/perform.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/liuzhiyi1992/WaveLoadingView/b8acc7f4af94921f4038d1a2516a45aed2fa5fce/WaveLoadingView/perform.gif
--------------------------------------------------------------------------------
/WaveLoadingViewTests/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | BNDL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 |
24 |
25 |
--------------------------------------------------------------------------------
/WaveLoadingViewTests/WaveLoadingViewTests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // WaveLoadingViewTests.swift
3 | // WaveLoadingViewTests
4 | //
5 | // Created by lzy on 15/12/30.
6 | // Copyright © 2015年 lzy. All rights reserved.
7 | //
8 |
9 | import XCTest
10 | @testable import WaveLoadingView
11 |
12 | class WaveLoadingViewTests: XCTestCase {
13 |
14 | override func setUp() {
15 | super.setUp()
16 | // Put setup code here. This method is called before the invocation of each test method in the class.
17 | }
18 |
19 | override func tearDown() {
20 | // Put teardown code here. This method is called after the invocation of each test method in the class.
21 | super.tearDown()
22 | }
23 |
24 | func testExample() {
25 | // This is an example of a functional test case.
26 | // Use XCTAssert and related functions to verify your tests produce the correct results.
27 | }
28 |
29 | func testPerformanceExample() {
30 | // This is an example of a performance test case.
31 | self.measureBlock {
32 | // Put the code you want to measure the time of here.
33 | }
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/WaveLoadingViewUITests/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | BNDL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 |
24 |
25 |
--------------------------------------------------------------------------------
/WaveLoadingViewUITests/WaveLoadingViewUITests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // WaveLoadingViewUITests.swift
3 | // WaveLoadingViewUITests
4 | //
5 | // Created by lzy on 15/12/30.
6 | // Copyright © 2015年 lzy. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class WaveLoadingViewUITests: XCTestCase {
12 |
13 | override func setUp() {
14 | super.setUp()
15 |
16 | // Put setup code here. This method is called before the invocation of each test method in the class.
17 |
18 | // In UI tests it is usually best to stop immediately when a failure occurs.
19 | continueAfterFailure = false
20 | // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
21 | XCUIApplication().launch()
22 |
23 | // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
24 | }
25 |
26 | override func tearDown() {
27 | // Put teardown code here. This method is called after the invocation of each test method in the class.
28 | super.tearDown()
29 | }
30 |
31 | func testExample() {
32 | // Use recording to get started writing UI tests.
33 | // Use XCTAssert and related functions to verify your tests produce the correct results.
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------