├── .gitignore ├── LICENSE ├── MusicPlay ├── MusicPlay.xcodeproj │ ├── project.pbxproj │ └── project.xcworkspace │ │ └── contents.xcworkspacedata ├── MusicPlay │ ├── AppDelegate.h │ ├── AppDelegate.m │ ├── Assets.xcassets │ │ ├── AppIcon.appiconset │ │ │ └── Contents.json │ │ ├── Contents.json │ │ └── ICON │ │ │ ├── Contents.json │ │ │ ├── forme_btn_stop.imageset │ │ │ ├── Contents.json │ │ │ └── forme_btn_stop@2x.png │ │ │ ├── hp_player_btn_next_normal.imageset │ │ │ ├── Contents.json │ │ │ └── hp_player_btn_next_normal@2x.png │ │ │ ├── hp_player_btn_pause_highlight.imageset │ │ │ ├── Contents.json │ │ │ └── hp_player_btn_pause_highlight@2x.png │ │ │ ├── hp_player_btn_pause_normal.imageset │ │ │ ├── Contents.json │ │ │ └── hp_player_btn_pause_normal@2x.png │ │ │ ├── hp_player_btn_play_highlight.imageset │ │ │ ├── Contents.json │ │ │ └── hp_player_btn_play_highlight@2x.png │ │ │ ├── hp_player_btn_play_normal.imageset │ │ │ ├── Contents.json │ │ │ └── hp_player_btn_play_normal@2x.png │ │ │ ├── hp_player_btn_pre_highlight.imageset │ │ │ ├── Contents.json │ │ │ └── hp_player_btn_pre_highlight@2x.png │ │ │ ├── hp_player_btn_pre_normal.imageset │ │ │ ├── Contents.json │ │ │ └── hp_player_btn_pre_normal@2x.png │ │ │ ├── ls_audio_showing_bg.imageset │ │ │ ├── Contents.json │ │ │ └── ls_audio_showing_bg.jpg │ │ │ ├── ls_live_audio_bg.imageset │ │ │ ├── Contents.json │ │ │ └── ls_live_audio_bg.jpg │ │ │ ├── player_btn_bz_sel_normal.imageset │ │ │ ├── Contents.json │ │ │ └── player_btn_bz_sel_normal@2x.png │ │ │ └── player_btn_sq_sel_normal.imageset │ │ │ ├── Contents.json │ │ │ └── player_btn_sq_sel_normal@2x.png │ ├── Base.lproj │ │ ├── LaunchScreen.storyboard │ │ └── Main.storyboard │ ├── Info.plist │ ├── MusicModel.h │ ├── MusicModel.m │ ├── SDWebImage │ │ ├── LICENSE │ │ ├── README.md │ │ └── 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.h │ ├── ViewController.m │ ├── main.m │ └── music.json ├── MusicPlayTests │ ├── Info.plist │ └── MusicPlayTests.m └── MusicPlayUITests │ ├── Info.plist │ └── MusicPlayUITests.m └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## Build generated 6 | build/ 7 | DerivedData/ 8 | 9 | ## Various settings 10 | *.pbxuser 11 | !default.pbxuser 12 | *.mode1v3 13 | !default.mode1v3 14 | *.mode2v3 15 | !default.mode2v3 16 | *.perspectivev3 17 | !default.perspectivev3 18 | xcuserdata/ 19 | 20 | ## Other 21 | *.moved-aside 22 | *.xcuserstate 23 | 24 | ## Obj-C/Swift specific 25 | *.hmap 26 | *.ipa 27 | *.dSYM.zip 28 | *.dSYM 29 | 30 | # CocoaPods 31 | # 32 | # We recommend against adding the Pods directory to your .gitignore. However 33 | # you should judge for yourself, the pros and cons are mentioned at: 34 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 35 | # 36 | # Pods/ 37 | 38 | # Carthage 39 | # 40 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 41 | # Carthage/Checkouts 42 | 43 | Carthage/Build 44 | 45 | # fastlane 46 | # 47 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 48 | # screenshots whenever they are needed. 49 | # For more information about the recommended setup visit: 50 | # https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md 51 | 52 | fastlane/report.xml 53 | fastlane/screenshots 54 | 55 | #Code Injection 56 | # 57 | # After new code Injection tools there's a generated folder /iOSInjectionProject 58 | # https://github.com/johnno1962/injectionforxcode 59 | 60 | iOSInjectionProject/ 61 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 yedexiong 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // MusicPlay 4 | // 5 | // Created by yedexiong on 16/11/3. 6 | // Copyright © 2016年 yoke121. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface AppDelegate : UIResponder 12 | 13 | @property (strong, nonatomic) UIWindow *window; 14 | 15 | 16 | 17 | 18 | @end 19 | 20 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // MusicPlay 4 | // 5 | // Created by yedexiong on 16/11/3. 6 | // Copyright © 2016年 yoke121. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | #import 11 | 12 | @interface AppDelegate () 13 | 14 | @end 15 | 16 | @implementation AppDelegate 17 | 18 | 19 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 20 | 21 | [application setStatusBarStyle:UIStatusBarStyleLightContent]; 22 | 23 | //获取音频会话11 24 | AVAudioSession *session = [AVAudioSession sharedInstance]; 25 | //设置类型是播放。 26 | [session setCategory:AVAudioSessionCategoryPlayback error:nil]; 27 | //激活音频会话。 28 | [session setActive:YES error:nil]; 29 | 30 | return YES; 31 | } 32 | 33 | 34 | - (void)applicationWillResignActive:(UIApplication *)application { 35 | // 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. 36 | // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. 37 | } 38 | 39 | 40 | - (void)applicationDidEnterBackground:(UIApplication *)application { 41 | // 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. 42 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 43 | } 44 | 45 | 46 | - (void)applicationWillEnterForeground:(UIApplication *)application { 47 | // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 48 | } 49 | 50 | 51 | - (void)applicationDidBecomeActive:(UIApplication *)application { 52 | // 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. 53 | } 54 | 55 | 56 | - (void)applicationWillTerminate:(UIApplication *)application { 57 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 58 | } 59 | 60 | 61 | @end 62 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "20x20", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "20x20", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "29x29", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "29x29", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "40x40", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "40x40", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "idiom" : "iphone", 35 | "size" : "60x60", 36 | "scale" : "2x" 37 | }, 38 | { 39 | "idiom" : "iphone", 40 | "size" : "60x60", 41 | "scale" : "3x" 42 | } 43 | ], 44 | "info" : { 45 | "version" : 1, 46 | "author" : "xcode" 47 | } 48 | } -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/forme_btn_stop.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "scale" : "1x" 6 | }, 7 | { 8 | "idiom" : "universal", 9 | "filename" : "forme_btn_stop@2x.png", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/forme_btn_stop.imageset/forme_btn_stop@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yedexiong/MsuicPlayDemo/d11ede94ba86c2a5448e8670f5fca5a9b7563e11/MusicPlay/MusicPlay/Assets.xcassets/ICON/forme_btn_stop.imageset/forme_btn_stop@2x.png -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_next_normal.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "scale" : "1x" 6 | }, 7 | { 8 | "idiom" : "universal", 9 | "filename" : "hp_player_btn_next_normal@2x.png", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_next_normal.imageset/hp_player_btn_next_normal@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yedexiong/MsuicPlayDemo/d11ede94ba86c2a5448e8670f5fca5a9b7563e11/MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_next_normal.imageset/hp_player_btn_next_normal@2x.png -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_pause_highlight.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "hp_player_btn_pause_highlight@2x.png", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_pause_highlight.imageset/hp_player_btn_pause_highlight@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yedexiong/MsuicPlayDemo/d11ede94ba86c2a5448e8670f5fca5a9b7563e11/MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_pause_highlight.imageset/hp_player_btn_pause_highlight@2x.png -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_pause_normal.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "scale" : "1x" 6 | }, 7 | { 8 | "idiom" : "universal", 9 | "filename" : "hp_player_btn_pause_normal@2x.png", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_pause_normal.imageset/hp_player_btn_pause_normal@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yedexiong/MsuicPlayDemo/d11ede94ba86c2a5448e8670f5fca5a9b7563e11/MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_pause_normal.imageset/hp_player_btn_pause_normal@2x.png -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_play_highlight.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "hp_player_btn_play_highlight@2x.png", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_play_highlight.imageset/hp_player_btn_play_highlight@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yedexiong/MsuicPlayDemo/d11ede94ba86c2a5448e8670f5fca5a9b7563e11/MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_play_highlight.imageset/hp_player_btn_play_highlight@2x.png -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_play_normal.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "scale" : "1x" 6 | }, 7 | { 8 | "idiom" : "universal", 9 | "filename" : "hp_player_btn_play_normal@2x.png", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_play_normal.imageset/hp_player_btn_play_normal@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yedexiong/MsuicPlayDemo/d11ede94ba86c2a5448e8670f5fca5a9b7563e11/MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_play_normal.imageset/hp_player_btn_play_normal@2x.png -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_pre_highlight.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "hp_player_btn_pre_highlight@2x.png", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_pre_highlight.imageset/hp_player_btn_pre_highlight@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yedexiong/MsuicPlayDemo/d11ede94ba86c2a5448e8670f5fca5a9b7563e11/MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_pre_highlight.imageset/hp_player_btn_pre_highlight@2x.png -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_pre_normal.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "scale" : "1x" 6 | }, 7 | { 8 | "idiom" : "universal", 9 | "filename" : "hp_player_btn_pre_normal@2x.png", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_pre_normal.imageset/hp_player_btn_pre_normal@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yedexiong/MsuicPlayDemo/d11ede94ba86c2a5448e8670f5fca5a9b7563e11/MusicPlay/MusicPlay/Assets.xcassets/ICON/hp_player_btn_pre_normal.imageset/hp_player_btn_pre_normal@2x.png -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/ls_audio_showing_bg.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "ls_audio_showing_bg.jpg", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/ls_audio_showing_bg.imageset/ls_audio_showing_bg.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yedexiong/MsuicPlayDemo/d11ede94ba86c2a5448e8670f5fca5a9b7563e11/MusicPlay/MusicPlay/Assets.xcassets/ICON/ls_audio_showing_bg.imageset/ls_audio_showing_bg.jpg -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/ls_live_audio_bg.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "ls_live_audio_bg.jpg", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/ls_live_audio_bg.imageset/ls_live_audio_bg.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yedexiong/MsuicPlayDemo/d11ede94ba86c2a5448e8670f5fca5a9b7563e11/MusicPlay/MusicPlay/Assets.xcassets/ICON/ls_live_audio_bg.imageset/ls_live_audio_bg.jpg -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/player_btn_bz_sel_normal.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "scale" : "1x" 6 | }, 7 | { 8 | "idiom" : "universal", 9 | "filename" : "player_btn_bz_sel_normal@2x.png", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/player_btn_bz_sel_normal.imageset/player_btn_bz_sel_normal@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yedexiong/MsuicPlayDemo/d11ede94ba86c2a5448e8670f5fca5a9b7563e11/MusicPlay/MusicPlay/Assets.xcassets/ICON/player_btn_bz_sel_normal.imageset/player_btn_bz_sel_normal@2x.png -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/player_btn_sq_sel_normal.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "scale" : "1x" 6 | }, 7 | { 8 | "idiom" : "universal", 9 | "filename" : "player_btn_sq_sel_normal@2x.png", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/Assets.xcassets/ICON/player_btn_sq_sel_normal.imageset/player_btn_sq_sel_normal@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yedexiong/MsuicPlayDemo/d11ede94ba86c2a5448e8670f5fca5a9b7563e11/MusicPlay/MusicPlay/Assets.xcassets/ICON/player_btn_sq_sel_normal.imageset/player_btn_sq_sel_normal@2x.png -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/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 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/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 | CFBundleVersion 20 | 1 21 | LSRequiresIPhoneOS 22 | 23 | NSAppTransportSecurity 24 | 25 | NSAllowsArbitraryLoads 26 | 27 | 28 | UIBackgroundModes 29 | 30 | audio 31 | 32 | UILaunchStoryboardName 33 | LaunchScreen 34 | UIMainStoryboardFile 35 | Main 36 | UIRequiredDeviceCapabilities 37 | 38 | armv7 39 | 40 | UISupportedInterfaceOrientations 41 | 42 | UIInterfaceOrientationPortrait 43 | UIInterfaceOrientationLandscapeLeft 44 | UIInterfaceOrientationLandscapeRight 45 | 46 | UIViewControllerBasedStatusBarAppearance 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/MusicModel.h: -------------------------------------------------------------------------------- 1 | // 2 | // MusicModel.h 3 | // MakeMoney 4 | // 5 | // Created by yedexiong on 16/10/27. 6 | // Copyright © 2016年 yoke121. All rights reserved. 7 | // 音乐模型 8 | 9 | #import 10 | 11 | 12 | 13 | @interface MusicModel : NSObject 14 | 15 | 16 | 17 | /** 18 | 歌曲编号 19 | */ 20 | @property(nonatomic,copy)NSNumber *Id; 21 | 22 | /** 23 | 歌名 24 | */ 25 | @property(nonatomic,strong) NSString *name; 26 | /** 27 | 歌曲作者 28 | */ 29 | @property(nonatomic,copy)NSString *artist; 30 | /** 31 | 32 | */ 33 | @property(nonatomic,copy)NSString *cover; 34 | /** 35 | 时长 36 | */ 37 | @property(nonatomic,copy)NSString *duration; 38 | /** 39 | 链接 40 | */ 41 | @property(nonatomic,copy)NSString *url; 42 | 43 | /** 44 | 是否正在播放 45 | */ 46 | @property(nonatomic,assign) BOOL isPlay; 47 | 48 | 49 | @property(nonatomic,strong) NSNumber *detailDuration; 50 | 51 | 52 | -(instancetype)initWithDic:(NSDictionary*)dic; 53 | 54 | 55 | @end 56 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/MusicModel.m: -------------------------------------------------------------------------------- 1 | // 2 | // MusicModel.m 3 | // MakeMoney 4 | // 5 | // Created by yedexiong on 16/10/27. 6 | // Copyright © 2016年 yoke121. All rights reserved. 7 | // 8 | 9 | #import "MusicModel.h" 10 | 11 | @implementation MusicModel 12 | 13 | -(NSNumber*)detailDuration 14 | { 15 | if (!_detailDuration) { 16 | 17 | NSArray *array = [self.duration componentsSeparatedByString:@":"]; 18 | 19 | if (array && array.count) { 20 | 21 | NSInteger time = [array[0] integerValue]*60 + [array[1] integerValue]; 22 | _detailDuration = @(time); 23 | } 24 | 25 | } 26 | return _detailDuration; 27 | } 28 | 29 | 30 | -(instancetype)initWithDic:(NSDictionary*)dic 31 | { 32 | if (self = [super init]) { 33 | [self setValuesForKeysWithDictionary:dic]; 34 | self.Id = dic[@"id"]; 35 | } 36 | return self; 37 | } 38 | 39 | -(void)setValue:(id)value forUndefinedKey:(NSString *)key 40 | { 41 | 42 | } 43 | 44 | 45 | @end 46 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Olivier Poitrey rs@dailymotion.com 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is furnished 8 | to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | 21 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/README.md: -------------------------------------------------------------------------------- 1 | Web Image 2 | ========= 3 | [![Build Status](http://img.shields.io/travis/rs/SDWebImage/master.svg?style=flat)](https://travis-ci.org/rs/SDWebImage) 4 | [![Pod Version](http://img.shields.io/cocoapods/v/SDWebImage.svg?style=flat)](http://cocoadocs.org/docsets/SDWebImage/) 5 | [![Pod Platform](http://img.shields.io/cocoapods/p/SDWebImage.svg?style=flat)](http://cocoadocs.org/docsets/SDWebImage/) 6 | [![Pod License](http://img.shields.io/cocoapods/l/SDWebImage.svg?style=flat)](https://www.apache.org/licenses/LICENSE-2.0.html) 7 | [![Dependency Status](https://www.versioneye.com/objective-c/sdwebimage/3.3/badge.svg?style=flat)](https://www.versioneye.com/objective-c/sdwebimage/3.3) 8 | [![Reference Status](https://www.versioneye.com/objective-c/sdwebimage/reference_badge.svg?style=flat)](https://www.versioneye.com/objective-c/sdwebimage/references) 9 | [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/rs/SDWebImage) 10 | 11 | This library provides a category for UIImageView with support for remote images coming from the web. 12 | 13 | It provides: 14 | 15 | - An `UIImageView` category adding web image and cache management to the Cocoa Touch framework 16 | - An asynchronous image downloader 17 | - An asynchronous memory + disk image caching with automatic cache expiration handling 18 | - Animated GIF support 19 | - WebP format support 20 | - A background image decompression 21 | - A guarantee that the same URL won't be downloaded several times 22 | - A guarantee that bogus URLs won't be retried again and again 23 | - A guarantee that main thread will never be blocked 24 | - Performances! 25 | - Use GCD and ARC 26 | - Arm64 support 27 | 28 | NOTE: Version 3.8 of SDWebImage requires iOS 7 or later (because of NSURLSession). 29 | Versions 3.7 to 3.0 requires iOS 5.1.1. If you need iOS < 5.0 support, please use the last [2.0 version](https://github.com/rs/SDWebImage/tree/2.0-compat). 30 | 31 | [How is SDWebImage better than X?](https://github.com/rs/SDWebImage/wiki/How-is-SDWebImage-better-than-X%3F) 32 | 33 | Who Uses It 34 | ---------- 35 | 36 | Find out [who uses SDWebImage](https://github.com/rs/SDWebImage/wiki/Who-Uses-SDWebImage) and add your app to the list. 37 | 38 | How To Use 39 | ---------- 40 | 41 | API documentation is available at [CocoaDocs - SDWebImage](http://cocoadocs.org/docsets/SDWebImage/) 42 | 43 | ### Using UIImageView+WebCache category with UITableView 44 | 45 | Just #import the UIImageView+WebCache.h header, and call the sd_setImageWithURL:placeholderImage: 46 | method from the tableView:cellForRowAtIndexPath: UITableViewDataSource method. Everything will be 47 | handled for you, from async downloads to caching management. 48 | 49 | ```objective-c 50 | #import 51 | 52 | ... 53 | 54 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 55 | static NSString *MyIdentifier = @"MyIdentifier"; 56 | 57 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 58 | if (cell == nil) { 59 | cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 60 | reuseIdentifier:MyIdentifier] autorelease]; 61 | } 62 | 63 | // Here we use the new provided sd_setImageWithURL: method to load the web image 64 | [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] 65 | placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; 66 | 67 | cell.textLabel.text = @"My Text"; 68 | return cell; 69 | } 70 | ``` 71 | 72 | ### Using blocks 73 | 74 | With blocks, you can be notified about the image download progress and whenever the image retrieval 75 | has completed with success or not: 76 | 77 | ```objective-c 78 | // Here we use the new provided sd_setImageWithURL: method to load the web image 79 | [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] 80 | placeholderImage:[UIImage imageNamed:@"placeholder.png"] 81 | completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 82 | ... completion code here ... 83 | }]; 84 | ``` 85 | 86 | Note: neither your success nor failure block will be call if your image request is canceled before completion. 87 | 88 | ### Using SDWebImageManager 89 | 90 | The SDWebImageManager is the class behind the UIImageView+WebCache category. It ties the 91 | asynchronous downloader with the image cache store. You can use this class directly to benefit 92 | from web image downloading with caching in another context than a UIView (ie: with Cocoa). 93 | 94 | Here is a simple example of how to use SDWebImageManager: 95 | 96 | ```objective-c 97 | SDWebImageManager *manager = [SDWebImageManager sharedManager]; 98 | [manager downloadImageWithURL:imageURL 99 | options:0 100 | progress:^(NSInteger receivedSize, NSInteger expectedSize) { 101 | // progression tracking code 102 | } 103 | completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 104 | if (image) { 105 | // do something with image 106 | } 107 | }]; 108 | ``` 109 | 110 | ### Using Asynchronous Image Downloader Independently 111 | 112 | It's also possible to use the async image downloader independently: 113 | 114 | ```objective-c 115 | SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader]; 116 | [downloader downloadImageWithURL:imageURL 117 | options:0 118 | progress:^(NSInteger receivedSize, NSInteger expectedSize) { 119 | // progression tracking code 120 | } 121 | completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) { 122 | if (image && finished) { 123 | // do something with image 124 | } 125 | }]; 126 | ``` 127 | 128 | ### Using Asynchronous Image Caching Independently 129 | 130 | It is also possible to use the async based image cache store independently. SDImageCache 131 | maintains a memory cache and an optional disk cache. Disk cache write operations are performed 132 | asynchronous so it doesn't add unnecessary latency to the UI. 133 | 134 | The SDImageCache class provides a singleton instance for convenience but you can create your own 135 | instance if you want to create separated cache namespace. 136 | 137 | To lookup the cache, you use the `queryDiskCacheForKey:done:` method. If the method returns nil, it means the cache 138 | doesn't currently own the image. You are thus responsible for generating and caching it. The cache 139 | key is an application unique identifier for the image to cache. It is generally the absolute URL of 140 | the image. 141 | 142 | ```objective-c 143 | SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:@"myNamespace"]; 144 | [imageCache queryDiskCacheForKey:myCacheKey done:^(UIImage *image) { 145 | // image is not nil if image was found 146 | }]; 147 | ``` 148 | 149 | By default SDImageCache will lookup the disk cache if an image can't be found in the memory cache. 150 | You can prevent this from happening by calling the alternative method `imageFromMemoryCacheForKey:`. 151 | 152 | To store an image into the cache, you use the storeImage:forKey: method: 153 | 154 | ```objective-c 155 | [[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey]; 156 | ``` 157 | 158 | By default, the image will be stored in memory cache as well as on disk cache (asynchronously). If 159 | you want only the memory cache, use the alternative method storeImage:forKey:toDisk: with a negative 160 | third argument. 161 | 162 | ### Using cache key filter 163 | 164 | Sometime, you may not want to use the image URL as cache key because part of the URL is dynamic 165 | (i.e.: for access control purpose). SDWebImageManager provides a way to set a cache key filter that 166 | takes the NSURL as input, and output a cache key NSString. 167 | 168 | The following example sets a filter in the application delegate that will remove any query-string from 169 | the URL before to use it as a cache key: 170 | 171 | ```objective-c 172 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 173 | SDWebImageManager.sharedManager.cacheKeyFilter = ^(NSURL *url) { 174 | url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; 175 | return [url absoluteString]; 176 | }; 177 | 178 | // Your app init code... 179 | return YES; 180 | } 181 | ``` 182 | 183 | 184 | Common Problems 185 | --------------- 186 | 187 | ### Using dynamic image size with UITableViewCell 188 | 189 | UITableView determines the size of the image by the first image set for a cell. If your remote images 190 | don't have the same size as your placeholder image, you may experience strange anamorphic scaling issue. 191 | The following article gives a way to workaround this issue: 192 | 193 | [http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/](http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/) 194 | 195 | 196 | ### Handle image refresh 197 | 198 | SDWebImage does very aggressive caching by default. It ignores all kind of caching control header returned by the HTTP server and cache the returned images with no time restriction. It implies your images URLs are static URLs pointing to images that never change. If the pointed image happen to change, some parts of the URL should change accordingly. 199 | 200 | If you don't control the image server you're using, you may not be able to change the URL when its content is updated. This is the case for Facebook avatar URLs for instance. In such case, you may use the `SDWebImageRefreshCached` flag. This will slightly degrade the performance but will respect the HTTP caching control headers: 201 | 202 | ``` objective-c 203 | [imageView sd_setImageWithURL:[NSURL URLWithString:@"https://graph.facebook.com/olivier.poitrey/picture"] 204 | placeholderImage:[UIImage imageNamed:@"avatar-placeholder.png"] 205 | options:SDWebImageRefreshCached]; 206 | ``` 207 | 208 | ### Add a progress indicator 209 | 210 | See this category: https://github.com/JJSaccolo/UIActivityIndicator-for-SDWebImage 211 | 212 | Installation 213 | ------------ 214 | 215 | There are three ways to use SDWebImage in your project: 216 | - using CocoaPods 217 | - copying all the files into your project 218 | - importing the project as a static library 219 | 220 | ### Installation with CocoaPods 221 | 222 | [CocoaPods](http://cocoapods.org/) is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries in your projects. See the [Get Started](http://cocoapods.org/#get_started) section for more details. 223 | 224 | #### Podfile 225 | ``` 226 | platform :ios, '7.0' 227 | pod 'SDWebImage', '~>3.8' 228 | ``` 229 | 230 | If you are using Swift, be sure to add `use_frameworks!` and set your target to iOS 8+: 231 | ``` 232 | platform :ios, '8.0' 233 | use_frameworks! 234 | ``` 235 | 236 | #### Subspecs 237 | 238 | There are 3 subspecs available now: `Core`, `MapKit` and `WebP` (this means you can install only some of the SDWebImage modules. By default, you get just `Core`, so if you need `WebP`, you need to specify it). 239 | 240 | Podfile example: 241 | ``` 242 | pod 'SDWebImage/WebP' 243 | ``` 244 | 245 | ### Installation with Carthage (iOS 8+) 246 | 247 | [Carthage](https://github.com/Carthage/Carthage) is a lightweight dependency manager for Swift and Objective-C. It leverages CocoaTouch modules and is less invasive than CocoaPods. 248 | 249 | To install with carthage, follow the instruction on [Carthage](https://github.com/Carthage/Carthage) 250 | 251 | #### Cartfile 252 | ``` 253 | github "rs/SDWebImage" 254 | ``` 255 | 256 | #### Usage 257 | Swift 258 | 259 | If you installed using CocoaPods: 260 | ``` 261 | import SDWebImage 262 | ``` 263 | 264 | If you installed manually: 265 | ``` 266 | import WebImage 267 | ``` 268 | 269 | Objective-C 270 | 271 | ``` 272 | @import WebImage; 273 | ``` 274 | 275 | ### Installation by cloning the repository 276 | 277 | In order to gain access to all the files from the repository, you should clone it. 278 | ``` 279 | git clone --recursive https://github.com/rs/SDWebImage.git 280 | ``` 281 | 282 | ### Add the SDWebImage project to your project 283 | 284 | - Download and unzip the last version of the framework from the [download page](https://github.com/rs/SDWebImage/releases) 285 | - Right-click on the project navigator and select "Add Files to "Your Project": 286 | - In the dialog, select SDWebImage.framework: 287 | - Check the "Copy items into destination group's folder (if needed)" checkbox 288 | 289 | ### Add dependencies 290 | 291 | - In you application project app’s target settings, find the "Build Phases" section and open the "Link Binary With Libraries" block: 292 | - Click the "+" button again and select the "ImageIO.framework", this is needed by the progressive download feature: 293 | 294 | ### Add Linker Flag 295 | 296 | Open the "Build Settings" tab, in the "Linking" section, locate the "Other Linker Flags" setting and add the "-ObjC" flag: 297 | 298 | ![Other Linker Flags](http://dl.dropbox.com/u/123346/SDWebImage/10_other_linker_flags.jpg) 299 | 300 | Alternatively, if this causes compilation problems with frameworks that extend optional libraries, such as Parse, RestKit or opencv2, instead of the -ObjC flag use: 301 | ``` 302 | -force_load SDWebImage.framework/Versions/Current/SDWebImage 303 | ``` 304 | 305 | If you're using Cocoa Pods and have any frameworks that extend optional libraries, such as Parsen RestKit or opencv2, instead of the -ObjC flag use: 306 | ``` 307 | -force_load $(TARGET_BUILD_DIR)/libPods.a 308 | ``` 309 | and this: 310 | ``` 311 | $(inherited) 312 | ``` 313 | 314 | ### Import headers in your source files 315 | 316 | In the source files where you need to use the library, import the header file: 317 | 318 | ```objective-c 319 | #import 320 | ``` 321 | 322 | ### Build Project 323 | 324 | At this point your workspace should build without error. If you are having problem, post to the Issue and the 325 | community can help you solve it. 326 | 327 | Future Enhancements 328 | ------------------- 329 | 330 | - LRU memory cache cleanup instead of reset on memory warning 331 | 332 | ## Licenses 333 | 334 | All source code is licensed under the [MIT License](https://raw.github.com/rs/SDWebImage/master/LICENSE). 335 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | * Decompressing images that are downloaded and cached can improve performance but can consume lot of memory. 41 | * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. 42 | */ 43 | @property (assign, nonatomic) BOOL shouldDecompressImages; 44 | 45 | /** 46 | * disable iCloud backup [defaults to YES] 47 | */ 48 | @property (assign, nonatomic) BOOL shouldDisableiCloud; 49 | 50 | /** 51 | * use memory cache [defaults to YES] 52 | */ 53 | @property (assign, nonatomic) BOOL shouldCacheImagesInMemory; 54 | 55 | /** 56 | * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. 57 | */ 58 | @property (assign, nonatomic) NSUInteger maxMemoryCost; 59 | 60 | /** 61 | * The maximum number of objects the cache should hold. 62 | */ 63 | @property (assign, nonatomic) NSUInteger maxMemoryCountLimit; 64 | 65 | /** 66 | * The maximum length of time to keep an image in the cache, in seconds 67 | */ 68 | @property (assign, nonatomic) NSInteger maxCacheAge; 69 | 70 | /** 71 | * The maximum size of the cache, in bytes. 72 | */ 73 | @property (assign, nonatomic) NSUInteger maxCacheSize; 74 | 75 | /** 76 | * Returns global shared cache instance 77 | * 78 | * @return SDImageCache global instance 79 | */ 80 | + (SDImageCache *)sharedImageCache; 81 | 82 | /** 83 | * Init a new cache store with a specific namespace 84 | * 85 | * @param ns The namespace to use for this cache store 86 | */ 87 | - (id)initWithNamespace:(NSString *)ns; 88 | 89 | /** 90 | * Init a new cache store with a specific namespace and directory 91 | * 92 | * @param ns The namespace to use for this cache store 93 | * @param directory Directory to cache disk images in 94 | */ 95 | - (id)initWithNamespace:(NSString *)ns diskCacheDirectory:(NSString *)directory; 96 | 97 | -(NSString *)makeDiskCachePath:(NSString*)fullNamespace; 98 | 99 | /** 100 | * Add a read-only cache path to search for images pre-cached by SDImageCache 101 | * Useful if you want to bundle pre-loaded images with your app 102 | * 103 | * @param path The path to use for this read-only cache path 104 | */ 105 | - (void)addReadOnlyCachePath:(NSString *)path; 106 | 107 | /** 108 | * Store an image into memory and disk cache at the given key. 109 | * 110 | * @param image The image to store 111 | * @param key The unique image cache key, usually it's image absolute URL 112 | */ 113 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key; 114 | 115 | /** 116 | * Store an image into memory and optionally disk cache at the given key. 117 | * 118 | * @param image The image to store 119 | * @param key The unique image cache key, usually it's image absolute URL 120 | * @param toDisk Store the image to disk cache if YES 121 | */ 122 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk; 123 | 124 | /** 125 | * Store an image into memory and optionally disk cache at the given key. 126 | * 127 | * @param image The image to store 128 | * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage 129 | * @param imageData The image data as returned by the server, this representation will be used for disk storage 130 | * instead of converting the given image object into a storable/compressed image format in order 131 | * to save quality and CPU 132 | * @param key The unique image cache key, usually it's image absolute URL 133 | * @param toDisk Store the image to disk cache if YES 134 | */ 135 | - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk; 136 | 137 | /** 138 | * Store image NSData into disk cache at the given key. 139 | * 140 | * @param imageData The image data to store 141 | * @param key The unique image cache key, usually it's image absolute URL 142 | */ 143 | - (void)storeImageDataToDisk:(NSData *)imageData forKey:(NSString *)key; 144 | 145 | /** 146 | * Query the disk cache asynchronously. 147 | * 148 | * @param key The unique key used to store the wanted image 149 | */ 150 | - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock; 151 | 152 | /** 153 | * Query the memory cache synchronously. 154 | * 155 | * @param key The unique key used to store the wanted image 156 | */ 157 | - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key; 158 | 159 | /** 160 | * Query the disk cache synchronously after checking the memory cache. 161 | * 162 | * @param key The unique key used to store the wanted image 163 | */ 164 | - (UIImage *)imageFromDiskCacheForKey:(NSString *)key; 165 | 166 | /** 167 | * Remove the image from memory and disk cache asynchronously 168 | * 169 | * @param key The unique image cache key 170 | */ 171 | - (void)removeImageForKey:(NSString *)key; 172 | 173 | 174 | /** 175 | * Remove the image from memory and disk cache asynchronously 176 | * 177 | * @param key The unique image cache key 178 | * @param completion An block that should be executed after the image has been removed (optional) 179 | */ 180 | - (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion; 181 | 182 | /** 183 | * Remove the image from memory and optionally disk cache asynchronously 184 | * 185 | * @param key The unique image cache key 186 | * @param fromDisk Also remove cache entry from disk if YES 187 | */ 188 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk; 189 | 190 | /** 191 | * Remove the image from memory and optionally disk cache asynchronously 192 | * 193 | * @param key The unique image cache key 194 | * @param fromDisk Also remove cache entry from disk if YES 195 | * @param completion An block that should be executed after the image has been removed (optional) 196 | */ 197 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion; 198 | 199 | /** 200 | * Clear all memory cached images 201 | */ 202 | - (void)clearMemory; 203 | 204 | /** 205 | * Clear all disk cached images. Non-blocking method - returns immediately. 206 | * @param completion An block that should be executed after cache expiration completes (optional) 207 | */ 208 | - (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion; 209 | 210 | /** 211 | * Clear all disk cached images 212 | * @see clearDiskOnCompletion: 213 | */ 214 | - (void)clearDisk; 215 | 216 | /** 217 | * Remove all expired cached image from disk. Non-blocking method - returns immediately. 218 | * @param completionBlock An block that should be executed after cache expiration completes (optional) 219 | */ 220 | - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock; 221 | 222 | /** 223 | * Remove all expired cached image from disk 224 | * @see cleanDiskWithCompletionBlock: 225 | */ 226 | - (void)cleanDisk; 227 | 228 | /** 229 | * Get the size used by the disk cache 230 | */ 231 | - (NSUInteger)getSize; 232 | 233 | /** 234 | * Get the number of images in the disk cache 235 | */ 236 | - (NSUInteger)getDiskCount; 237 | 238 | /** 239 | * Asynchronously calculate the disk cache's size. 240 | */ 241 | - (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock; 242 | 243 | /** 244 | * Async check if image exists in disk cache already (does not load the image) 245 | * 246 | * @param key the key describing the url 247 | * @param completionBlock the block to be executed when the check is done. 248 | * @note the completion block will be always executed on the main queue 249 | */ 250 | - (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 251 | 252 | /** 253 | * Check if image exists in disk cache already (does not load the image) 254 | * 255 | * @param key the key describing the url 256 | * 257 | * @return YES if an image exists for the given key 258 | */ 259 | - (BOOL)diskImageExistsWithKey:(NSString *)key; 260 | 261 | /** 262 | * Get the cache path for a certain key (needs the cache path root folder) 263 | * 264 | * @param key the key (can be obtained from url using cacheKeyForURL) 265 | * @param path the cache path root folder 266 | * 267 | * @return the cache path 268 | */ 269 | - (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path; 270 | 271 | /** 272 | * Get the default cache path for a certain key 273 | * 274 | * @param key the key (can be obtained from url using cacheKeyForURL) 275 | * 276 | * @return the default cache path 277 | */ 278 | - (NSString *)defaultCachePathForKey:(NSString *)key; 279 | 280 | @end 281 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 != 20000 && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0 17 | #error SDWebImage doesn't support Deployment 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 | extern NSString *const SDWebImageErrorDomain; 59 | 60 | #define dispatch_main_sync_safe(block)\ 61 | if ([NSThread isMainThread]) {\ 62 | block();\ 63 | } else {\ 64 | dispatch_sync(dispatch_get_main_queue(), block);\ 65 | } 66 | 67 | #define dispatch_main_async_safe(block)\ 68 | if ([NSThread isMainThread]) {\ 69 | block();\ 70 | } else {\ 71 | dispatch_async(dispatch_get_main_queue(), block);\ 72 | } 73 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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; 32 | if (key.length >= 8) { 33 | NSRange range = [key rangeOfString:@"@2x."]; 34 | if (range.location != NSNotFound) { 35 | scale = 2.0; 36 | } 37 | 38 | range = [key rangeOfString:@"@3x."]; 39 | if (range.location != NSNotFound) { 40 | scale = 3.0; 41 | } 42 | } 43 | 44 | UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; 45 | image = scaledImage; 46 | } 47 | return image; 48 | } 49 | } 50 | 51 | NSString *const SDWebImageErrorDomain = @"SDWebImageErrorDomain"; 52 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | // while downloading huge amount of images 17 | // autorelease the bitmap context 18 | // and all vars to help system to free memory 19 | // when there are memory warning. 20 | // on iOS7, do not forget to call 21 | // [[SDImageCache sharedImageCache] clearMemory]; 22 | 23 | if (image == nil) { // Prevent "CGBitmapContextCreateImage: invalid context 0x0" error 24 | return nil; 25 | } 26 | 27 | @autoreleasepool{ 28 | // do not decode animated images 29 | if (image.images != nil) { 30 | return image; 31 | } 32 | 33 | CGImageRef imageRef = image.CGImage; 34 | 35 | CGImageAlphaInfo alpha = CGImageGetAlphaInfo(imageRef); 36 | BOOL anyAlpha = (alpha == kCGImageAlphaFirst || 37 | alpha == kCGImageAlphaLast || 38 | alpha == kCGImageAlphaPremultipliedFirst || 39 | alpha == kCGImageAlphaPremultipliedLast); 40 | if (anyAlpha) { 41 | return image; 42 | } 43 | 44 | // current 45 | CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(CGImageGetColorSpace(imageRef)); 46 | CGColorSpaceRef colorspaceRef = CGImageGetColorSpace(imageRef); 47 | 48 | BOOL unsupportedColorSpace = (imageColorSpaceModel == kCGColorSpaceModelUnknown || 49 | imageColorSpaceModel == kCGColorSpaceModelMonochrome || 50 | imageColorSpaceModel == kCGColorSpaceModelCMYK || 51 | imageColorSpaceModel == kCGColorSpaceModelIndexed); 52 | if (unsupportedColorSpace) { 53 | colorspaceRef = CGColorSpaceCreateDeviceRGB(); 54 | } 55 | 56 | size_t width = CGImageGetWidth(imageRef); 57 | size_t height = CGImageGetHeight(imageRef); 58 | NSUInteger bytesPerPixel = 4; 59 | NSUInteger bytesPerRow = bytesPerPixel * width; 60 | NSUInteger bitsPerComponent = 8; 61 | 62 | 63 | // kCGImageAlphaNone is not supported in CGBitmapContextCreate. 64 | // Since the original image here has no alpha info, use kCGImageAlphaNoneSkipLast 65 | // to create bitmap graphics contexts without alpha info. 66 | CGContextRef context = CGBitmapContextCreate(NULL, 67 | width, 68 | height, 69 | bitsPerComponent, 70 | bytesPerRow, 71 | colorspaceRef, 72 | kCGBitmapByteOrderDefault|kCGImageAlphaNoneSkipLast); 73 | 74 | // Draw the image into the context and retrieve the new bitmap image without alpha 75 | CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); 76 | CGImageRef imageRefWithoutAlpha = CGBitmapContextCreateImage(context); 77 | UIImage *imageWithoutAlpha = [UIImage imageWithCGImage:imageRefWithoutAlpha 78 | scale:image.scale 79 | orientation:image.imageOrientation]; 80 | 81 | if (unsupportedColorSpace) { 82 | CGColorSpaceRelease(colorspaceRef); 83 | } 84 | 85 | CGContextRelease(context); 86 | CGImageRelease(imageRefWithoutAlpha); 87 | 88 | return imageWithoutAlpha; 89 | } 90 | } 91 | 92 | @end 93 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 use 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 certificates. 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 | typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { 55 | /** 56 | * Default value. All download operations will execute in queue style (first-in-first-out). 57 | */ 58 | SDWebImageDownloaderFIFOExecutionOrder, 59 | 60 | /** 61 | * All download operations will execute in stack style (last-in-first-out). 62 | */ 63 | SDWebImageDownloaderLIFOExecutionOrder 64 | }; 65 | 66 | extern NSString *const SDWebImageDownloadStartNotification; 67 | extern NSString *const SDWebImageDownloadStopNotification; 68 | 69 | typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); 70 | 71 | typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished); 72 | 73 | typedef NSDictionary *(^SDWebImageDownloaderHeadersFilterBlock)(NSURL *url, NSDictionary *headers); 74 | 75 | /** 76 | * Asynchronous downloader dedicated and optimized for image loading. 77 | */ 78 | @interface SDWebImageDownloader : NSObject 79 | 80 | /** 81 | * Decompressing images that are downloaded and cached can improve performance but can consume lot of memory. 82 | * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. 83 | */ 84 | @property (assign, nonatomic) BOOL shouldDecompressImages; 85 | 86 | @property (assign, nonatomic) NSInteger maxConcurrentDownloads; 87 | 88 | /** 89 | * Shows the current amount of downloads that still need to be downloaded 90 | */ 91 | @property (readonly, nonatomic) NSUInteger currentDownloadCount; 92 | 93 | 94 | /** 95 | * The timeout value (in seconds) for the download operation. Default: 15.0. 96 | */ 97 | @property (assign, nonatomic) NSTimeInterval downloadTimeout; 98 | 99 | 100 | /** 101 | * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. 102 | */ 103 | @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; 104 | 105 | /** 106 | * Singleton method, returns the shared instance 107 | * 108 | * @return global shared instance of downloader class 109 | */ 110 | + (SDWebImageDownloader *)sharedDownloader; 111 | 112 | /** 113 | * Set the default URL credential to be set for request operations. 114 | */ 115 | @property (strong, nonatomic) NSURLCredential *urlCredential; 116 | 117 | /** 118 | * Set username 119 | */ 120 | @property (strong, nonatomic) NSString *username; 121 | 122 | /** 123 | * Set password 124 | */ 125 | @property (strong, nonatomic) NSString *password; 126 | 127 | /** 128 | * Set filter to pick headers for downloading image HTTP request. 129 | * 130 | * This block will be invoked for each downloading image request, returned 131 | * NSDictionary will be used as headers in corresponding HTTP request. 132 | */ 133 | @property (nonatomic, copy) SDWebImageDownloaderHeadersFilterBlock headersFilter; 134 | 135 | /** 136 | * Set a value for a HTTP header to be appended to each download HTTP request. 137 | * 138 | * @param value The value for the header field. Use `nil` value to remove the header. 139 | * @param field The name of the header field to set. 140 | */ 141 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field; 142 | 143 | /** 144 | * Returns the value of the specified HTTP header field. 145 | * 146 | * @return The value associated with the header field field, or `nil` if there is no corresponding header field. 147 | */ 148 | - (NSString *)valueForHTTPHeaderField:(NSString *)field; 149 | 150 | /** 151 | * Sets a subclass of `SDWebImageDownloaderOperation` as the default 152 | * `NSOperation` to be used each time SDWebImage constructs a request 153 | * operation to download an image. 154 | * 155 | * @param operationClass The subclass of `SDWebImageDownloaderOperation` to set 156 | * as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`. 157 | */ 158 | - (void)setOperationClass:(Class)operationClass; 159 | 160 | /** 161 | * Creates a SDWebImageDownloader async downloader instance with a given URL 162 | * 163 | * The delegate will be informed when the image is finish downloaded or an error has happen. 164 | * 165 | * @see SDWebImageDownloaderDelegate 166 | * 167 | * @param url The URL to the image to download 168 | * @param options The options to be used for this download 169 | * @param progressBlock A block called repeatedly while the image is downloading 170 | * @param completedBlock A block called once the download is completed. 171 | * If the download succeeded, the image parameter is set, in case of error, 172 | * error parameter is set with the error. The last parameter is always YES 173 | * if SDWebImageDownloaderProgressiveDownload isn't use. With the 174 | * SDWebImageDownloaderProgressiveDownload option, this block is called 175 | * repeatedly with the partial image object and the finished argument set to NO 176 | * before to be called a last time with the full image and finished argument 177 | * set to YES. In case of error, the finished argument is always YES. 178 | * 179 | * @return A cancellable SDWebImageOperation 180 | */ 181 | - (id )downloadImageWithURL:(NSURL *)url 182 | options:(SDWebImageDownloaderOptions)options 183 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 184 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock; 185 | 186 | /** 187 | * Sets the download queue suspension state 188 | */ 189 | - (void)setSuspended:(BOOL)suspended; 190 | 191 | /** 192 | * Cancels all download operations in the queue 193 | */ 194 | - (void)cancelAllDownloads; 195 | 196 | @end 197 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | static NSString *const kProgressCallbackKey = @"progress"; 14 | static NSString *const kCompletedCallbackKey = @"completed"; 15 | 16 | @interface SDWebImageDownloader () 17 | 18 | @property (strong, nonatomic) NSOperationQueue *downloadQueue; 19 | @property (weak, nonatomic) NSOperation *lastAddedOperation; 20 | @property (assign, nonatomic) Class operationClass; 21 | @property (strong, nonatomic) NSMutableDictionary *URLCallbacks; 22 | @property (strong, nonatomic) NSMutableDictionary *HTTPHeaders; 23 | // This queue is used to serialize the handling of the network responses of all the download operation in a single queue 24 | @property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t barrierQueue; 25 | 26 | // The session in which data tasks will run 27 | @property (strong, nonatomic) NSURLSession *session; 28 | 29 | @end 30 | 31 | @implementation SDWebImageDownloader 32 | 33 | + (void)initialize { 34 | // Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator ) 35 | // To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import 36 | if (NSClassFromString(@"SDNetworkActivityIndicator")) { 37 | 38 | #pragma clang diagnostic push 39 | #pragma clang diagnostic ignored "-Warc-performSelector-leaks" 40 | id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")]; 41 | #pragma clang diagnostic pop 42 | 43 | // Remove observer in case it was previously added. 44 | [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil]; 45 | [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil]; 46 | 47 | [[NSNotificationCenter defaultCenter] addObserver:activityIndicator 48 | selector:NSSelectorFromString(@"startActivity") 49 | name:SDWebImageDownloadStartNotification object:nil]; 50 | [[NSNotificationCenter defaultCenter] addObserver:activityIndicator 51 | selector:NSSelectorFromString(@"stopActivity") 52 | name:SDWebImageDownloadStopNotification object:nil]; 53 | } 54 | } 55 | 56 | + (SDWebImageDownloader *)sharedDownloader { 57 | static dispatch_once_t once; 58 | static id instance; 59 | dispatch_once(&once, ^{ 60 | instance = [self new]; 61 | }); 62 | return instance; 63 | } 64 | 65 | - (id)init { 66 | if ((self = [super init])) { 67 | _operationClass = [SDWebImageDownloaderOperation class]; 68 | _shouldDecompressImages = YES; 69 | _executionOrder = SDWebImageDownloaderFIFOExecutionOrder; 70 | _downloadQueue = [NSOperationQueue new]; 71 | _downloadQueue.maxConcurrentOperationCount = 6; 72 | _downloadQueue.name = @"com.hackemist.SDWebImageDownloader"; 73 | _URLCallbacks = [NSMutableDictionary new]; 74 | #ifdef SD_WEBP 75 | _HTTPHeaders = [@{@"Accept": @"image/webp,image/*;q=0.8"} mutableCopy]; 76 | #else 77 | _HTTPHeaders = [@{@"Accept": @"image/*;q=0.8"} mutableCopy]; 78 | #endif 79 | _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT); 80 | _downloadTimeout = 15.0; 81 | 82 | NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; 83 | sessionConfig.timeoutIntervalForRequest = _downloadTimeout; 84 | 85 | /** 86 | * Create the session for this task 87 | * We send nil as delegate queue so that the session creates a serial operation queue for performing all delegate 88 | * method calls and completion handler calls. 89 | */ 90 | self.session = [NSURLSession sessionWithConfiguration:sessionConfig 91 | delegate:self 92 | delegateQueue:nil]; 93 | } 94 | return self; 95 | } 96 | 97 | - (void)dealloc { 98 | [self.session invalidateAndCancel]; 99 | self.session = nil; 100 | 101 | [self.downloadQueue cancelAllOperations]; 102 | SDDispatchQueueRelease(_barrierQueue); 103 | } 104 | 105 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field { 106 | if (value) { 107 | self.HTTPHeaders[field] = value; 108 | } 109 | else { 110 | [self.HTTPHeaders removeObjectForKey:field]; 111 | } 112 | } 113 | 114 | - (NSString *)valueForHTTPHeaderField:(NSString *)field { 115 | return self.HTTPHeaders[field]; 116 | } 117 | 118 | - (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads { 119 | _downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads; 120 | } 121 | 122 | - (NSUInteger)currentDownloadCount { 123 | return _downloadQueue.operationCount; 124 | } 125 | 126 | - (NSInteger)maxConcurrentDownloads { 127 | return _downloadQueue.maxConcurrentOperationCount; 128 | } 129 | 130 | - (void)setOperationClass:(Class)operationClass { 131 | _operationClass = operationClass ?: [SDWebImageDownloaderOperation class]; 132 | } 133 | 134 | - (id )downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock { 135 | __block SDWebImageDownloaderOperation *operation; 136 | __weak __typeof(self)wself = self; 137 | 138 | [self addProgressCallback:progressBlock completedBlock:completedBlock forURL:url createCallback:^{ 139 | NSTimeInterval timeoutInterval = wself.downloadTimeout; 140 | if (timeoutInterval == 0.0) { 141 | timeoutInterval = 15.0; 142 | } 143 | 144 | // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise 145 | NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval]; 146 | request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies); 147 | request.HTTPShouldUsePipelining = YES; 148 | if (wself.headersFilter) { 149 | request.allHTTPHeaderFields = wself.headersFilter(url, [wself.HTTPHeaders copy]); 150 | } 151 | else { 152 | request.allHTTPHeaderFields = wself.HTTPHeaders; 153 | } 154 | operation = [[wself.operationClass alloc] initWithRequest:request 155 | inSession:self.session 156 | options:options 157 | progress:^(NSInteger receivedSize, NSInteger expectedSize) { 158 | SDWebImageDownloader *sself = wself; 159 | if (!sself) return; 160 | __block NSArray *callbacksForURL; 161 | dispatch_sync(sself.barrierQueue, ^{ 162 | callbacksForURL = [sself.URLCallbacks[url] copy]; 163 | }); 164 | for (NSDictionary *callbacks in callbacksForURL) { 165 | dispatch_async(dispatch_get_main_queue(), ^{ 166 | SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey]; 167 | if (callback) callback(receivedSize, expectedSize); 168 | }); 169 | } 170 | } 171 | completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) { 172 | SDWebImageDownloader *sself = wself; 173 | if (!sself) return; 174 | __block NSArray *callbacksForURL; 175 | dispatch_barrier_sync(sself.barrierQueue, ^{ 176 | callbacksForURL = [sself.URLCallbacks[url] copy]; 177 | if (finished) { 178 | [sself.URLCallbacks removeObjectForKey:url]; 179 | } 180 | }); 181 | for (NSDictionary *callbacks in callbacksForURL) { 182 | SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey]; 183 | if (callback) callback(image, data, error, finished); 184 | } 185 | } 186 | cancelled:^{ 187 | SDWebImageDownloader *sself = wself; 188 | if (!sself) return; 189 | dispatch_barrier_async(sself.barrierQueue, ^{ 190 | [sself.URLCallbacks removeObjectForKey:url]; 191 | }); 192 | }]; 193 | operation.shouldDecompressImages = wself.shouldDecompressImages; 194 | 195 | if (wself.urlCredential) { 196 | operation.credential = wself.urlCredential; 197 | } else if (wself.username && wself.password) { 198 | operation.credential = [NSURLCredential credentialWithUser:wself.username password:wself.password persistence:NSURLCredentialPersistenceForSession]; 199 | } 200 | 201 | if (options & SDWebImageDownloaderHighPriority) { 202 | operation.queuePriority = NSOperationQueuePriorityHigh; 203 | } else if (options & SDWebImageDownloaderLowPriority) { 204 | operation.queuePriority = NSOperationQueuePriorityLow; 205 | } 206 | 207 | [wself.downloadQueue addOperation:operation]; 208 | if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) { 209 | // Emulate LIFO execution order by systematically adding new operations as last operation's dependency 210 | [wself.lastAddedOperation addDependency:operation]; 211 | wself.lastAddedOperation = operation; 212 | } 213 | }]; 214 | 215 | return operation; 216 | } 217 | 218 | - (void)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock completedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock forURL:(NSURL *)url createCallback:(SDWebImageNoParamsBlock)createCallback { 219 | // 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. 220 | if (url == nil) { 221 | if (completedBlock != nil) { 222 | completedBlock(nil, nil, nil, NO); 223 | } 224 | return; 225 | } 226 | 227 | dispatch_barrier_sync(self.barrierQueue, ^{ 228 | BOOL first = NO; 229 | if (!self.URLCallbacks[url]) { 230 | self.URLCallbacks[url] = [NSMutableArray new]; 231 | first = YES; 232 | } 233 | 234 | // Handle single download of simultaneous download request for the same URL 235 | NSMutableArray *callbacksForURL = self.URLCallbacks[url]; 236 | NSMutableDictionary *callbacks = [NSMutableDictionary new]; 237 | if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy]; 238 | if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy]; 239 | [callbacksForURL addObject:callbacks]; 240 | self.URLCallbacks[url] = callbacksForURL; 241 | 242 | if (first) { 243 | createCallback(); 244 | } 245 | }); 246 | } 247 | 248 | - (void)setSuspended:(BOOL)suspended { 249 | [self.downloadQueue setSuspended:suspended]; 250 | } 251 | 252 | - (void)cancelAllDownloads { 253 | [self.downloadQueue cancelAllOperations]; 254 | } 255 | 256 | #pragma mark Helper methods 257 | 258 | - (SDWebImageDownloaderOperation *)operationWithTask:(NSURLSessionTask *)task { 259 | SDWebImageDownloaderOperation *returnOperation = nil; 260 | for (SDWebImageDownloaderOperation *operation in self.downloadQueue.operations) { 261 | if (operation.dataTask.taskIdentifier == task.taskIdentifier) { 262 | returnOperation = operation; 263 | break; 264 | } 265 | } 266 | return returnOperation; 267 | } 268 | 269 | #pragma mark NSURLSessionDataDelegate 270 | 271 | - (void)URLSession:(NSURLSession *)session 272 | dataTask:(NSURLSessionDataTask *)dataTask 273 | didReceiveResponse:(NSURLResponse *)response 274 | completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { 275 | 276 | // Identify the operation that runs this task and pass it the delegate method 277 | SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:dataTask]; 278 | 279 | [dataOperation URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler]; 280 | } 281 | 282 | - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { 283 | 284 | // Identify the operation that runs this task and pass it the delegate method 285 | SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:dataTask]; 286 | 287 | [dataOperation URLSession:session dataTask:dataTask didReceiveData:data]; 288 | } 289 | 290 | - (void)URLSession:(NSURLSession *)session 291 | dataTask:(NSURLSessionDataTask *)dataTask 292 | willCacheResponse:(NSCachedURLResponse *)proposedResponse 293 | completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler { 294 | 295 | // Identify the operation that runs this task and pass it the delegate method 296 | SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:dataTask]; 297 | 298 | [dataOperation URLSession:session dataTask:dataTask willCacheResponse:proposedResponse completionHandler:completionHandler]; 299 | } 300 | 301 | #pragma mark NSURLSessionTaskDelegate 302 | 303 | - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { 304 | // Identify the operation that runs this task and pass it the delegate method 305 | SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:task]; 306 | 307 | [dataOperation URLSession:session task:task didCompleteWithError:error]; 308 | } 309 | 310 | - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { 311 | 312 | // Identify the operation that runs this task and pass it the delegate method 313 | SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:task]; 314 | 315 | [dataOperation URLSession:session task:task didReceiveChallenge:challenge completionHandler:completionHandler]; 316 | } 317 | 318 | @end 319 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | extern NSString *const SDWebImageDownloadStartNotification; 14 | extern NSString *const SDWebImageDownloadReceiveResponseNotification; 15 | extern NSString *const SDWebImageDownloadStopNotification; 16 | extern NSString *const SDWebImageDownloadFinishNotification; 17 | 18 | @interface SDWebImageDownloaderOperation : NSOperation 19 | 20 | /** 21 | * The request used by the operation's task. 22 | */ 23 | @property (strong, nonatomic, readonly) NSURLRequest *request; 24 | 25 | /** 26 | * The operation's task 27 | */ 28 | @property (strong, nonatomic, readonly) NSURLSessionTask *dataTask; 29 | 30 | 31 | @property (assign, nonatomic) BOOL shouldDecompressImages; 32 | 33 | /** 34 | * Was used to determine whether the URL connection should consult the credential storage for authenticating the connection. 35 | * @deprecated Not used for a couple of versions 36 | */ 37 | @property (nonatomic, assign) BOOL shouldUseCredentialStorage __deprecated_msg("Property deprecated. Does nothing. Kept only for backwards compatibility"); 38 | 39 | /** 40 | * The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. 41 | * 42 | * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. 43 | */ 44 | @property (nonatomic, strong) NSURLCredential *credential; 45 | 46 | /** 47 | * The SDWebImageDownloaderOptions for the receiver. 48 | */ 49 | @property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; 50 | 51 | /** 52 | * The expected size of data. 53 | */ 54 | @property (assign, nonatomic) NSInteger expectedSize; 55 | 56 | /** 57 | * The response returned by the operation's connection. 58 | */ 59 | @property (strong, nonatomic) NSURLResponse *response; 60 | 61 | /** 62 | * Initializes a `SDWebImageDownloaderOperation` object 63 | * 64 | * @see SDWebImageDownloaderOperation 65 | * 66 | * @param request the URL request 67 | * @param session the URL session in which this operation will run 68 | * @param options downloader options 69 | * @param progressBlock the block executed when a new chunk of data arrives. 70 | * @note the progress block is executed on a background queue 71 | * @param completedBlock the block executed when the download is done. 72 | * @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 73 | * @param cancelBlock the block executed if the download (operation) is cancelled 74 | * 75 | * @return the initialized instance 76 | */ 77 | - (id)initWithRequest:(NSURLRequest *)request 78 | inSession:(NSURLSession *)session 79 | options:(SDWebImageDownloaderOptions)options 80 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 81 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock 82 | cancelled:(SDWebImageNoParamsBlock)cancelBlock; 83 | 84 | /** 85 | * Initializes a `SDWebImageDownloaderOperation` object 86 | * 87 | * @see SDWebImageDownloaderOperation 88 | * 89 | * @param request the URL request 90 | * @param options downloader options 91 | * @param progressBlock the block executed when a new chunk of data arrives. 92 | * @note the progress block is executed on a background queue 93 | * @param completedBlock the block executed when the download is done. 94 | * @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 95 | * @param cancelBlock the block executed if the download (operation) is cancelled 96 | * 97 | * @return the initialized instance. The operation will run in a separate session created for this operation 98 | */ 99 | - (id)initWithRequest:(NSURLRequest *)request 100 | options:(SDWebImageDownloaderOptions)options 101 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 102 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock 103 | cancelled:(SDWebImageNoParamsBlock)cancelBlock 104 | __deprecated_msg("Method deprecated. Use `initWithRequest:inSession:options:progress:completed:cancelled`"); 105 | 106 | @end 107 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 embedded 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 certificates. 62 | * Useful for testing purposes. Use with caution in production. 63 | */ 64 | SDWebImageAllowInvalidSSLCertificates = 1 << 7, 65 | 66 | /** 67 | * By default, images are loaded in the order in which they were queued. This flag moves them to 68 | * the front of the queue. 69 | */ 70 | SDWebImageHighPriority = 1 << 8, 71 | 72 | /** 73 | * By default, placeholder images are loaded while the image is loading. This flag will delay the loading 74 | * of the placeholder image until after the image has finished loading. 75 | */ 76 | SDWebImageDelayPlaceholder = 1 << 9, 77 | 78 | /** 79 | * We usually don't call transformDownloadedImage delegate method on animated images, 80 | * as most transformation code would mangle it. 81 | * Use this flag to transform them anyway. 82 | */ 83 | SDWebImageTransformAnimatedImage = 1 << 10, 84 | 85 | /** 86 | * By default, image is added to the imageView after download. But in some cases, we want to 87 | * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance) 88 | * Use this flag if you want to manually set the image in the completion when success 89 | */ 90 | SDWebImageAvoidAutoSetImage = 1 << 11 91 | }; 92 | 93 | typedef void(^SDWebImageCompletionBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL); 94 | 95 | typedef void(^SDWebImageCompletionWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL); 96 | 97 | typedef NSString *(^SDWebImageCacheKeyFilterBlock)(NSURL *url); 98 | 99 | 100 | @class SDWebImageManager; 101 | 102 | @protocol SDWebImageManagerDelegate 103 | 104 | @optional 105 | 106 | /** 107 | * Controls which image should be downloaded when the image is not found in the cache. 108 | * 109 | * @param imageManager The current `SDWebImageManager` 110 | * @param imageURL The url of the image to be downloaded 111 | * 112 | * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. 113 | */ 114 | - (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL; 115 | 116 | /** 117 | * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. 118 | * NOTE: This method is called from a global queue in order to not to block the main thread. 119 | * 120 | * @param imageManager The current `SDWebImageManager` 121 | * @param image The image to transform 122 | * @param imageURL The url of the image to transform 123 | * 124 | * @return The transformed image object. 125 | */ 126 | - (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL; 127 | 128 | @end 129 | 130 | /** 131 | * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. 132 | * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). 133 | * You can use this class directly to benefit from web image downloading with caching in another context than 134 | * a UIView. 135 | * 136 | * Here is a simple example of how to use SDWebImageManager: 137 | * 138 | * @code 139 | 140 | SDWebImageManager *manager = [SDWebImageManager sharedManager]; 141 | [manager downloadImageWithURL:imageURL 142 | options:0 143 | progress:nil 144 | completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 145 | if (image) { 146 | // do something with image 147 | } 148 | }]; 149 | 150 | * @endcode 151 | */ 152 | @interface SDWebImageManager : NSObject 153 | 154 | @property (weak, nonatomic) id delegate; 155 | 156 | @property (strong, nonatomic, readonly) SDImageCache *imageCache; 157 | @property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader; 158 | 159 | /** 160 | * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can 161 | * be used to remove dynamic part of an image URL. 162 | * 163 | * The following example sets a filter in the application delegate that will remove any query-string from the 164 | * URL before to use it as a cache key: 165 | * 166 | * @code 167 | 168 | [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) { 169 | url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; 170 | return [url absoluteString]; 171 | }]; 172 | 173 | * @endcode 174 | */ 175 | @property (nonatomic, copy) SDWebImageCacheKeyFilterBlock cacheKeyFilter; 176 | 177 | /** 178 | * Returns global SDWebImageManager instance. 179 | * 180 | * @return SDWebImageManager shared instance 181 | */ 182 | + (SDWebImageManager *)sharedManager; 183 | 184 | /** 185 | * Allows to specify instance of cache and image downloader used with image manager. 186 | * @return new instance of `SDWebImageManager` with specified cache and downloader. 187 | */ 188 | - (instancetype)initWithCache:(SDImageCache *)cache downloader:(SDWebImageDownloader *)downloader; 189 | 190 | /** 191 | * Downloads the image at the given URL if not present in cache or return the cached version otherwise. 192 | * 193 | * @param url The URL to the image 194 | * @param options A mask to specify options to use for this request 195 | * @param progressBlock A block called while image is downloading 196 | * @param completedBlock A block called when operation has been completed. 197 | * 198 | * This parameter is required. 199 | * 200 | * This block has no return value and takes the requested UIImage as first parameter. 201 | * In case of error the image parameter is nil and the second parameter may contain an NSError. 202 | * 203 | * The third parameter is an `SDImageCacheType` enum indicating if the image was retrieved from the local cache 204 | * or from the memory cache or from the network. 205 | * 206 | * The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is 207 | * downloading. This block is thus called repeatedly with a partial image. When image is fully downloaded, the 208 | * block is called a last time with the full image and the last parameter set to YES. 209 | * 210 | * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation 211 | */ 212 | - (id )downloadImageWithURL:(NSURL *)url 213 | options:(SDWebImageOptions)options 214 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 215 | completed:(SDWebImageCompletionWithFinishedBlock)completedBlock; 216 | 217 | /** 218 | * Saves image to cache for given URL 219 | * 220 | * @param image The image to cache 221 | * @param url The URL to the image 222 | * 223 | */ 224 | 225 | - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url; 226 | 227 | /** 228 | * Cancel all current operations 229 | */ 230 | - (void)cancelAll; 231 | 232 | /** 233 | * Check one or more operations running 234 | */ 235 | - (BOOL)isRunning; 236 | 237 | /** 238 | * Check if image has already been cached 239 | * 240 | * @param url image url 241 | * 242 | * @return if the image was already cached 243 | */ 244 | - (BOOL)cachedImageExistsForURL:(NSURL *)url; 245 | 246 | /** 247 | * Check if image has already been cached on disk only 248 | * 249 | * @param url image url 250 | * 251 | * @return if the image was already cached (disk only) 252 | */ 253 | - (BOOL)diskImageExistsForURL:(NSURL *)url; 254 | 255 | /** 256 | * Async check if image has already been cached 257 | * 258 | * @param url image url 259 | * @param completionBlock the block to be executed when the check is finished 260 | * 261 | * @note the completion block is always executed on the main queue 262 | */ 263 | - (void)cachedImageExistsForURL:(NSURL *)url 264 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 265 | 266 | /** 267 | * Async check if image has already been cached on disk only 268 | * 269 | * @param url image url 270 | * @param completionBlock the block to be executed when the check is finished 271 | * 272 | * @note the completion block is always executed on the main queue 273 | */ 274 | - (void)diskImageExistsForURL:(NSURL *)url 275 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 276 | 277 | 278 | /** 279 | *Return the cache key for a given URL 280 | */ 281 | - (NSString *)cacheKeyForURL:(NSURL *)url; 282 | 283 | @end 284 | 285 | 286 | #pragma mark - Deprecated 287 | 288 | typedef void(^SDWebImageCompletedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionBlock`"); 289 | typedef void(^SDWebImageCompletedWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionWithFinishedBlock`"); 290 | 291 | 292 | @interface SDWebImageManager (Deprecated) 293 | 294 | /** 295 | * Downloads the image at the given URL if not present in cache or return the cached version otherwise. 296 | * 297 | * @deprecated This method has been deprecated. Use `downloadImageWithURL:options:progress:completed:` 298 | */ 299 | - (id )downloadWithURL:(NSURL *)url 300 | options:(SDWebImageOptions)options 301 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 302 | completed:(SDWebImageCompletedWithFinishedBlock)completedBlock __deprecated_msg("Method deprecated. Use `downloadImageWithURL:options:progress:completed:`"); 303 | 304 | @end 305 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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) NSMutableSet *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 | - (instancetype)init { 41 | SDImageCache *cache = [SDImageCache sharedImageCache]; 42 | SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader]; 43 | return [self initWithCache:cache downloader:downloader]; 44 | } 45 | 46 | - (instancetype)initWithCache:(SDImageCache *)cache downloader:(SDWebImageDownloader *)downloader { 47 | if ((self = [super init])) { 48 | _imageCache = cache; 49 | _imageDownloader = downloader; 50 | _failedURLs = [NSMutableSet new]; 51 | _runningOperations = [NSMutableArray new]; 52 | } 53 | return self; 54 | } 55 | 56 | - (NSString *)cacheKeyForURL:(NSURL *)url { 57 | if (!url) { 58 | return @""; 59 | } 60 | 61 | if (self.cacheKeyFilter) { 62 | return self.cacheKeyFilter(url); 63 | } else { 64 | return [url absoluteString]; 65 | } 66 | } 67 | 68 | - (BOOL)cachedImageExistsForURL:(NSURL *)url { 69 | NSString *key = [self cacheKeyForURL:url]; 70 | if ([self.imageCache imageFromMemoryCacheForKey:key] != nil) return YES; 71 | return [self.imageCache diskImageExistsWithKey:key]; 72 | } 73 | 74 | - (BOOL)diskImageExistsForURL:(NSURL *)url { 75 | NSString *key = [self cacheKeyForURL:url]; 76 | return [self.imageCache diskImageExistsWithKey:key]; 77 | } 78 | 79 | - (void)cachedImageExistsForURL:(NSURL *)url 80 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock { 81 | NSString *key = [self cacheKeyForURL:url]; 82 | 83 | BOOL isInMemoryCache = ([self.imageCache imageFromMemoryCacheForKey:key] != nil); 84 | 85 | if (isInMemoryCache) { 86 | // making sure we call the completion block on the main queue 87 | dispatch_async(dispatch_get_main_queue(), ^{ 88 | if (completionBlock) { 89 | completionBlock(YES); 90 | } 91 | }); 92 | return; 93 | } 94 | 95 | [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { 96 | // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch 97 | if (completionBlock) { 98 | completionBlock(isInDiskCache); 99 | } 100 | }]; 101 | } 102 | 103 | - (void)diskImageExistsForURL:(NSURL *)url 104 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock { 105 | NSString *key = [self cacheKeyForURL:url]; 106 | 107 | [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { 108 | // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch 109 | if (completionBlock) { 110 | completionBlock(isInDiskCache); 111 | } 112 | }]; 113 | } 114 | 115 | - (id )downloadImageWithURL:(NSURL *)url 116 | options:(SDWebImageOptions)options 117 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 118 | completed:(SDWebImageCompletionWithFinishedBlock)completedBlock { 119 | // Invoking this method without a completedBlock is pointless 120 | NSAssert(completedBlock != nil, @"If you mean to prefetch the image, use -[SDWebImagePrefetcher prefetchURLs] instead"); 121 | 122 | // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, XCode won't 123 | // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString. 124 | if ([url isKindOfClass:NSString.class]) { 125 | url = [NSURL URLWithString:(NSString *)url]; 126 | } 127 | 128 | // Prevents app crashing on argument type error like sending NSNull instead of NSURL 129 | if (![url isKindOfClass:NSURL.class]) { 130 | url = nil; 131 | } 132 | 133 | __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new]; 134 | __weak SDWebImageCombinedOperation *weakOperation = operation; 135 | 136 | BOOL isFailedUrl = NO; 137 | @synchronized (self.failedURLs) { 138 | isFailedUrl = [self.failedURLs containsObject:url]; 139 | } 140 | 141 | if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) { 142 | dispatch_main_sync_safe(^{ 143 | NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]; 144 | completedBlock(nil, error, SDImageCacheTypeNone, YES, url); 145 | }); 146 | return operation; 147 | } 148 | 149 | @synchronized (self.runningOperations) { 150 | [self.runningOperations addObject:operation]; 151 | } 152 | NSString *key = [self cacheKeyForURL:url]; 153 | 154 | operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) { 155 | if (operation.isCancelled) { 156 | @synchronized (self.runningOperations) { 157 | [self.runningOperations removeObject:operation]; 158 | } 159 | 160 | return; 161 | } 162 | 163 | if ((!image || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) { 164 | if (image && options & SDWebImageRefreshCached) { 165 | dispatch_main_sync_safe(^{ 166 | // If image was found in the cache but SDWebImageRefreshCached is provided, notify about the cached image 167 | // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server. 168 | completedBlock(image, nil, cacheType, YES, url); 169 | }); 170 | } 171 | 172 | // download if no image or requested to refresh anyway, and download allowed by delegate 173 | SDWebImageDownloaderOptions downloaderOptions = 0; 174 | if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority; 175 | if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload; 176 | if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache; 177 | if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground; 178 | if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies; 179 | if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates; 180 | if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority; 181 | if (image && options & SDWebImageRefreshCached) { 182 | // force progressive off if image already cached but forced refreshing 183 | downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload; 184 | // ignore image read from NSURLCache if image if cached but force refreshing 185 | downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse; 186 | } 187 | id subOperation = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *data, NSError *error, BOOL finished) { 188 | __strong __typeof(weakOperation) strongOperation = weakOperation; 189 | if (!strongOperation || strongOperation.isCancelled) { 190 | // Do nothing if the operation was cancelled 191 | // See #699 for more details 192 | // 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 193 | } 194 | else if (error) { 195 | dispatch_main_sync_safe(^{ 196 | if (strongOperation && !strongOperation.isCancelled) { 197 | completedBlock(nil, error, SDImageCacheTypeNone, finished, url); 198 | } 199 | }); 200 | 201 | if ( error.code != NSURLErrorNotConnectedToInternet 202 | && error.code != NSURLErrorCancelled 203 | && error.code != NSURLErrorTimedOut 204 | && error.code != NSURLErrorInternationalRoamingOff 205 | && error.code != NSURLErrorDataNotAllowed 206 | && error.code != NSURLErrorCannotFindHost 207 | && error.code != NSURLErrorCannotConnectToHost) { 208 | @synchronized (self.failedURLs) { 209 | [self.failedURLs addObject:url]; 210 | } 211 | } 212 | } 213 | else { 214 | if ((options & SDWebImageRetryFailed)) { 215 | @synchronized (self.failedURLs) { 216 | [self.failedURLs removeObject:url]; 217 | } 218 | } 219 | 220 | BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly); 221 | 222 | if (options & SDWebImageRefreshCached && image && !downloadedImage) { 223 | // Image refresh hit the NSURLCache cache, do not call the completion block 224 | } 225 | else if (downloadedImage && (!downloadedImage.images || (options & SDWebImageTransformAnimatedImage)) && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) { 226 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 227 | UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url]; 228 | 229 | if (transformedImage && finished) { 230 | BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage]; 231 | [self.imageCache storeImage:transformedImage recalculateFromImage:imageWasTransformed imageData:(imageWasTransformed ? nil : data) forKey:key toDisk:cacheOnDisk]; 232 | } 233 | 234 | dispatch_main_sync_safe(^{ 235 | if (strongOperation && !strongOperation.isCancelled) { 236 | completedBlock(transformedImage, nil, SDImageCacheTypeNone, finished, url); 237 | } 238 | }); 239 | }); 240 | } 241 | else { 242 | if (downloadedImage && finished) { 243 | [self.imageCache storeImage:downloadedImage recalculateFromImage:NO imageData:data forKey:key toDisk:cacheOnDisk]; 244 | } 245 | 246 | dispatch_main_sync_safe(^{ 247 | if (strongOperation && !strongOperation.isCancelled) { 248 | completedBlock(downloadedImage, nil, SDImageCacheTypeNone, finished, url); 249 | } 250 | }); 251 | } 252 | } 253 | 254 | if (finished) { 255 | @synchronized (self.runningOperations) { 256 | if (strongOperation) { 257 | [self.runningOperations removeObject:strongOperation]; 258 | } 259 | } 260 | } 261 | }]; 262 | operation.cancelBlock = ^{ 263 | [subOperation cancel]; 264 | 265 | @synchronized (self.runningOperations) { 266 | __strong __typeof(weakOperation) strongOperation = weakOperation; 267 | if (strongOperation) { 268 | [self.runningOperations removeObject:strongOperation]; 269 | } 270 | } 271 | }; 272 | } 273 | else if (image) { 274 | dispatch_main_sync_safe(^{ 275 | __strong __typeof(weakOperation) strongOperation = weakOperation; 276 | if (strongOperation && !strongOperation.isCancelled) { 277 | completedBlock(image, nil, cacheType, YES, url); 278 | } 279 | }); 280 | @synchronized (self.runningOperations) { 281 | [self.runningOperations removeObject:operation]; 282 | } 283 | } 284 | else { 285 | // Image not in cache and download disallowed by delegate 286 | dispatch_main_sync_safe(^{ 287 | __strong __typeof(weakOperation) strongOperation = weakOperation; 288 | if (strongOperation && !weakOperation.isCancelled) { 289 | completedBlock(nil, nil, SDImageCacheTypeNone, YES, url); 290 | } 291 | }); 292 | @synchronized (self.runningOperations) { 293 | [self.runningOperations removeObject:operation]; 294 | } 295 | } 296 | }]; 297 | 298 | return operation; 299 | } 300 | 301 | - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url { 302 | if (image && url) { 303 | NSString *key = [self cacheKeyForURL:url]; 304 | [self.imageCache storeImage:image forKey:key toDisk:YES]; 305 | } 306 | } 307 | 308 | - (void)cancelAll { 309 | @synchronized (self.runningOperations) { 310 | NSArray *copiedOperations = [self.runningOperations copy]; 311 | [copiedOperations makeObjectsPerformSelector:@selector(cancel)]; 312 | [self.runningOperations removeObjectsInArray:copiedOperations]; 313 | } 314 | } 315 | 316 | - (BOOL)isRunning { 317 | BOOL isRunning = NO; 318 | @synchronized(self.runningOperations) { 319 | isRunning = (self.runningOperations.count > 0); 320 | } 321 | return isRunning; 322 | } 323 | 324 | @end 325 | 326 | 327 | @implementation SDWebImageCombinedOperation 328 | 329 | - (void)setCancelBlock:(SDWebImageNoParamsBlock)cancelBlock { 330 | // check if the operation is already cancelled, then we just call the cancelBlock 331 | if (self.isCancelled) { 332 | if (cancelBlock) { 333 | cancelBlock(); 334 | } 335 | _cancelBlock = nil; // don't forget to nil the cancelBlock, otherwise we will get crashes 336 | } else { 337 | _cancelBlock = [cancelBlock copy]; 338 | } 339 | } 340 | 341 | - (void)cancel { 342 | self.cancelled = YES; 343 | if (self.cacheOperation) { 344 | [self.cacheOperation cancel]; 345 | self.cacheOperation = nil; 346 | } 347 | if (self.cancelBlock) { 348 | self.cancelBlock(); 349 | 350 | // TODO: this is a temporary fix to #809. 351 | // Until we can figure the exact cause of the crash, going with the ivar instead of the setter 352 | // self.cancelBlock = nil; 353 | _cancelBlock = nil; 354 | } 355 | } 356 | 357 | @end 358 | 359 | 360 | @implementation SDWebImageManager (Deprecated) 361 | 362 | // deprecated method, uses the non deprecated method 363 | // adapter for the completion block 364 | - (id )downloadWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedWithFinishedBlock)completedBlock { 365 | return [self downloadImageWithURL:url 366 | options:options 367 | progress:progressBlock 368 | completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 369 | if (completedBlock) { 370 | completedBlock(image, error, cacheType, finished); 371 | } 372 | }]; 373 | } 374 | 375 | @end 376 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | /** 62 | * Queue options for Prefetcher. Defaults to Main Queue. 63 | */ 64 | @property (nonatomic, assign) dispatch_queue_t prefetcherQueue; 65 | 66 | @property (weak, nonatomic) id delegate; 67 | 68 | /** 69 | * Return the global image prefetcher instance. 70 | */ 71 | + (SDWebImagePrefetcher *)sharedImagePrefetcher; 72 | 73 | /** 74 | * Allows you to instantiate a prefetcher with any arbitrary image manager. 75 | */ 76 | - (id)initWithImageManager:(SDWebImageManager *)manager; 77 | 78 | /** 79 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, 80 | * currently one image is downloaded at a time, 81 | * and skips images for failed downloads and proceed to the next image in the list 82 | * 83 | * @param urls list of URLs to prefetch 84 | */ 85 | - (void)prefetchURLs:(NSArray *)urls; 86 | 87 | /** 88 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, 89 | * currently one image is downloaded at a time, 90 | * and skips images for failed downloads and proceed to the next image in the list 91 | * 92 | * @param urls list of URLs to prefetch 93 | * @param progressBlock block to be called when progress updates; 94 | * first parameter is the number of completed (successful or not) requests, 95 | * second parameter is the total number of images originally requested to be prefetched 96 | * @param completionBlock block to be called when prefetching is completed 97 | * first param is the number of completed (successful or not) requests, 98 | * second parameter is the number of skipped requests 99 | */ 100 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock; 101 | 102 | /** 103 | * Remove and cancel queued list 104 | */ 105 | - (void)cancelPrefetching; 106 | 107 | 108 | @end 109 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | @interface SDWebImagePrefetcher () 12 | 13 | @property (strong, nonatomic) SDWebImageManager *manager; 14 | @property (strong, nonatomic) NSArray *prefetchURLs; 15 | @property (assign, nonatomic) NSUInteger requestedCount; 16 | @property (assign, nonatomic) NSUInteger skippedCount; 17 | @property (assign, nonatomic) NSUInteger finishedCount; 18 | @property (assign, nonatomic) NSTimeInterval startedTime; 19 | @property (copy, nonatomic) SDWebImagePrefetcherCompletionBlock completionBlock; 20 | @property (copy, nonatomic) SDWebImagePrefetcherProgressBlock progressBlock; 21 | 22 | @end 23 | 24 | @implementation SDWebImagePrefetcher 25 | 26 | + (SDWebImagePrefetcher *)sharedImagePrefetcher { 27 | static dispatch_once_t once; 28 | static id instance; 29 | dispatch_once(&once, ^{ 30 | instance = [self new]; 31 | }); 32 | return instance; 33 | } 34 | 35 | - (id)init { 36 | return [self initWithImageManager:[SDWebImageManager new]]; 37 | } 38 | 39 | - (id)initWithImageManager:(SDWebImageManager *)manager { 40 | if ((self = [super init])) { 41 | _manager = manager; 42 | _options = SDWebImageLowPriority; 43 | _prefetcherQueue = dispatch_get_main_queue(); 44 | self.maxConcurrentDownloads = 3; 45 | } 46 | return self; 47 | } 48 | 49 | - (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads { 50 | self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads; 51 | } 52 | 53 | - (NSUInteger)maxConcurrentDownloads { 54 | return self.manager.imageDownloader.maxConcurrentDownloads; 55 | } 56 | 57 | - (void)startPrefetchingAtIndex:(NSUInteger)index { 58 | if (index >= self.prefetchURLs.count) return; 59 | self.requestedCount++; 60 | [self.manager downloadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 61 | if (!finished) return; 62 | self.finishedCount++; 63 | 64 | if (image) { 65 | if (self.progressBlock) { 66 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]); 67 | } 68 | } 69 | else { 70 | if (self.progressBlock) { 71 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]); 72 | } 73 | // Add last failed 74 | self.skippedCount++; 75 | } 76 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) { 77 | [self.delegate imagePrefetcher:self 78 | didPrefetchURL:self.prefetchURLs[index] 79 | finishedCount:self.finishedCount 80 | totalCount:self.prefetchURLs.count 81 | ]; 82 | } 83 | if (self.prefetchURLs.count > self.requestedCount) { 84 | dispatch_async(self.prefetcherQueue, ^{ 85 | [self startPrefetchingAtIndex:self.requestedCount]; 86 | }); 87 | } else if (self.finishedCount == self.requestedCount) { 88 | [self reportStatus]; 89 | if (self.completionBlock) { 90 | self.completionBlock(self.finishedCount, self.skippedCount); 91 | self.completionBlock = nil; 92 | } 93 | self.progressBlock = nil; 94 | } 95 | }]; 96 | } 97 | 98 | - (void)reportStatus { 99 | NSUInteger total = [self.prefetchURLs count]; 100 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) { 101 | [self.delegate imagePrefetcher:self 102 | didFinishWithTotalCount:(total - self.skippedCount) 103 | skippedCount:self.skippedCount 104 | ]; 105 | } 106 | } 107 | 108 | - (void)prefetchURLs:(NSArray *)urls { 109 | [self prefetchURLs:urls progress:nil completed:nil]; 110 | } 111 | 112 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock { 113 | [self cancelPrefetching]; // Prevent duplicate prefetch request 114 | self.startedTime = CFAbsoluteTimeGetCurrent(); 115 | self.prefetchURLs = urls; 116 | self.completionBlock = completionBlock; 117 | self.progressBlock = progressBlock; 118 | 119 | if (urls.count == 0) { 120 | if (completionBlock) { 121 | completionBlock(0,0); 122 | } 123 | } else { 124 | // Starts prefetching from the very first image on the list with the max allowed concurrency 125 | NSUInteger listCount = self.prefetchURLs.count; 126 | for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) { 127 | [self startPrefetchingAtIndex:i]; 128 | } 129 | } 130 | } 131 | 132 | - (void)cancelPrefetching { 133 | self.prefetchURLs = nil; 134 | self.skippedCount = 0; 135 | self.requestedCount = 0; 136 | self.finishedCount = 0; 137 | [self.manager cancelAll]; 138 | } 139 | 140 | @end 141 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 retrieved from the local cache or from the network. 74 | * The fourth 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 retrieved from the local cache or from the network. 90 | * The fourth 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 retrieved from the local cache or from the network. 107 | * The fourth 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 retrieved from the local cache or from the network. 156 | * The fourth 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 retrieved from the local cache or from the network. 172 | * The fourth 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 retrieved from the local cache or from the network. 188 | * The fourth 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 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | if (completedBlock) { 61 | NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 62 | completedBlock(nil, error, SDImageCacheTypeNone, url); 63 | } 64 | }); 65 | 66 | return; 67 | } 68 | 69 | self.imageURLStorage[@(state)] = url; 70 | 71 | __weak __typeof(self)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 && (options & SDWebImageAvoidAutoSetImage) && completedBlock) 78 | { 79 | completedBlock(image, error, cacheType, url); 80 | return; 81 | } 82 | else if (image) { 83 | [sself setImage:image forState:state]; 84 | } 85 | if (completedBlock && finished) { 86 | completedBlock(image, error, cacheType, url); 87 | } 88 | }); 89 | }]; 90 | [self sd_setImageLoadOperation:operation forState:state]; 91 | } 92 | 93 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state { 94 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; 95 | } 96 | 97 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { 98 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; 99 | } 100 | 101 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 102 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; 103 | } 104 | 105 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock { 106 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; 107 | } 108 | 109 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { 110 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; 111 | } 112 | 113 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 114 | [self sd_cancelBackgroundImageLoadForState:state]; 115 | 116 | [self setBackgroundImage:placeholder forState:state]; 117 | 118 | if (url) { 119 | __weak __typeof(self)wself = self; 120 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 121 | if (!wself) return; 122 | dispatch_main_sync_safe(^{ 123 | __strong UIButton *sself = wself; 124 | if (!sself) return; 125 | if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock) 126 | { 127 | completedBlock(image, error, cacheType, url); 128 | return; 129 | } 130 | else if (image) { 131 | [sself setBackgroundImage:image forState:state]; 132 | } 133 | if (completedBlock && finished) { 134 | completedBlock(image, error, cacheType, url); 135 | } 136 | }); 137 | }]; 138 | [self sd_setBackgroundImageLoadOperation:operation forState:state]; 139 | } else { 140 | dispatch_main_async_safe(^{ 141 | NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 142 | if (completedBlock) { 143 | completedBlock(nil, error, SDImageCacheTypeNone, url); 144 | } 145 | }); 146 | } 147 | } 148 | 149 | - (void)sd_setImageLoadOperation:(id)operation forState:(UIControlState)state { 150 | [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; 151 | } 152 | 153 | - (void)sd_cancelImageLoadForState:(UIControlState)state { 154 | [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; 155 | } 156 | 157 | - (void)sd_setBackgroundImageLoadOperation:(id)operation forState:(UIControlState)state { 158 | [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; 159 | } 160 | 161 | - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state { 162 | [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; 163 | } 164 | 165 | - (NSMutableDictionary *)imageURLStorage { 166 | NSMutableDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey); 167 | if (!storage) 168 | { 169 | storage = [NSMutableDictionary dictionary]; 170 | objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 171 | } 172 | 173 | return storage; 174 | } 175 | 176 | @end 177 | 178 | 179 | @implementation UIButton (WebCacheDeprecated) 180 | 181 | - (NSURL *)currentImageURL { 182 | return [self sd_currentImageURL]; 183 | } 184 | 185 | - (NSURL *)imageURLForState:(UIControlState)state { 186 | return [self sd_imageURLForState:state]; 187 | } 188 | 189 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state { 190 | [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; 191 | } 192 | 193 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { 194 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; 195 | } 196 | 197 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 198 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; 199 | } 200 | 201 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock { 202 | [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 203 | if (completedBlock) { 204 | completedBlock(image, error, cacheType); 205 | } 206 | }]; 207 | } 208 | 209 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { 210 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 211 | if (completedBlock) { 212 | completedBlock(image, error, cacheType); 213 | } 214 | }]; 215 | } 216 | 217 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { 218 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 219 | if (completedBlock) { 220 | completedBlock(image, error, cacheType); 221 | } 222 | }]; 223 | } 224 | 225 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state { 226 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; 227 | } 228 | 229 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { 230 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; 231 | } 232 | 233 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 234 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; 235 | } 236 | 237 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock { 238 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 239 | if (completedBlock) { 240 | completedBlock(image, error, cacheType); 241 | } 242 | }]; 243 | } 244 | 245 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { 246 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 247 | if (completedBlock) { 248 | completedBlock(image, error, cacheType); 249 | } 250 | }]; 251 | } 252 | 253 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { 254 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 255 | if (completedBlock) { 256 | completedBlock(image, error, cacheType); 257 | } 258 | }]; 259 | } 260 | 261 | - (void)cancelCurrentImageLoad { 262 | // in a backwards compatible manner, cancel for current state 263 | [self sd_cancelImageLoadForState:self.state]; 264 | } 265 | 266 | - (void)cancelBackgroundImageLoadForState:(UIControlState)state { 267 | [self sd_cancelBackgroundImageLoadForState:state]; 268 | } 269 | 270 | @end 271 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | if (!image) { 36 | continue; 37 | } 38 | 39 | duration += [self sd_frameDurationAtIndex:i source:source]; 40 | 41 | [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]]; 42 | 43 | CGImageRelease(image); 44 | } 45 | 46 | if (!duration) { 47 | duration = (1.0f / 10.0f) * count; 48 | } 49 | 50 | animatedImage = [UIImage animatedImageWithImages:images duration:duration]; 51 | } 52 | 53 | CFRelease(source); 54 | 55 | return animatedImage; 56 | } 57 | 58 | + (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source { 59 | float frameDuration = 0.1f; 60 | CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil); 61 | NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties; 62 | NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary]; 63 | 64 | NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime]; 65 | if (delayTimeUnclampedProp) { 66 | frameDuration = [delayTimeUnclampedProp floatValue]; 67 | } 68 | else { 69 | 70 | NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime]; 71 | if (delayTimeProp) { 72 | frameDuration = [delayTimeProp floatValue]; 73 | } 74 | } 75 | 76 | // Many annoying ads specify a 0 duration to make an image flash as quickly as possible. 77 | // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify 78 | // a duration of <= 10 ms. See and 79 | // for more information. 80 | 81 | if (frameDuration < 0.011f) { 82 | frameDuration = 0.100f; 83 | } 84 | 85 | CFRelease(cfFrameProperties); 86 | return frameDuration; 87 | } 88 | 89 | + (UIImage *)sd_animatedGIFNamed:(NSString *)name { 90 | CGFloat scale = [UIScreen mainScreen].scale; 91 | 92 | if (scale > 1.0f) { 93 | NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"]; 94 | 95 | NSData *data = [NSData dataWithContentsOfFile:retinaPath]; 96 | 97 | if (data) { 98 | return [UIImage sd_animatedGIFWithData:data]; 99 | } 100 | 101 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; 102 | 103 | data = [NSData dataWithContentsOfFile:path]; 104 | 105 | if (data) { 106 | return [UIImage sd_animatedGIFWithData:data]; 107 | } 108 | 109 | return [UIImage imageNamed:name]; 110 | } 111 | else { 112 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; 113 | 114 | NSData *data = [NSData dataWithContentsOfFile:path]; 115 | 116 | if (data) { 117 | return [UIImage sd_animatedGIFWithData:data]; 118 | } 119 | 120 | return [UIImage imageNamed:name]; 121 | } 122 | } 123 | 124 | - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size { 125 | if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) { 126 | return self; 127 | } 128 | 129 | CGSize scaledSize = size; 130 | CGPoint thumbnailPoint = CGPointZero; 131 | 132 | CGFloat widthFactor = size.width / self.size.width; 133 | CGFloat heightFactor = size.height / self.size.height; 134 | CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor; 135 | scaledSize.width = self.size.width * scaleFactor; 136 | scaledSize.height = self.size.height * scaleFactor; 137 | 138 | if (widthFactor > heightFactor) { 139 | thumbnailPoint.y = (size.height - scaledSize.height) * 0.5; 140 | } 141 | else if (widthFactor < heightFactor) { 142 | thumbnailPoint.x = (size.width - scaledSize.width) * 0.5; 143 | } 144 | 145 | NSMutableArray *scaledImages = [NSMutableArray array]; 146 | 147 | for (UIImage *image in self.images) { 148 | UIGraphicsBeginImageContextWithOptions(size, NO, 0.0); 149 | 150 | [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)]; 151 | UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 152 | 153 | [scaledImages addObject:newImage]; 154 | 155 | UIGraphicsEndImageContext(); 156 | } 157 | 158 | return [UIImage animatedImageWithImages:scaledImages duration:self.duration]; 159 | } 160 | 161 | @end 162 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | if (!data) { 22 | return nil; 23 | } 24 | 25 | UIImage *image; 26 | NSString *imageContentType = [NSData sd_contentTypeForImageData:data]; 27 | if ([imageContentType isEqualToString:@"image/gif"]) { 28 | image = [UIImage sd_animatedGIFWithData:data]; 29 | } 30 | #ifdef SD_WEBP 31 | else if ([imageContentType isEqualToString:@"image/webp"]) 32 | { 33 | image = [UIImage sd_imageWithWebPData:data]; 34 | } 35 | #endif 36 | else { 37 | image = [[UIImage alloc] initWithData:data]; 38 | UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data]; 39 | if (orientation != UIImageOrientationUp) { 40 | image = [UIImage imageWithCGImage:image.CGImage 41 | scale:image.scale 42 | orientation:orientation]; 43 | } 44 | } 45 | 46 | 47 | return image; 48 | } 49 | 50 | 51 | +(UIImageOrientation)sd_imageOrientationFromImageData:(NSData *)imageData { 52 | UIImageOrientation result = UIImageOrientationUp; 53 | CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL); 54 | if (imageSource) { 55 | CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); 56 | if (properties) { 57 | CFTypeRef val; 58 | int exifOrientation; 59 | val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); 60 | if (val) { 61 | CFNumberGetValue(val, kCFNumberIntType, &exifOrientation); 62 | result = [self sd_exifOrientationToiOSOrientation:exifOrientation]; 63 | } // else - if it's not set it remains at up 64 | CFRelease((CFTypeRef) properties); 65 | } else { 66 | //NSLog(@"NO PROPERTIES, FAIL"); 67 | } 68 | CFRelease(imageSource); 69 | } 70 | return result; 71 | } 72 | 73 | #pragma mark EXIF orientation tag converter 74 | // Convert an EXIF image orientation to an iOS one. 75 | // reference see here: http://sylvana.net/jpegcrop/exif_orientation.html 76 | + (UIImageOrientation) sd_exifOrientationToiOSOrientation:(int)exifOrientation { 77 | UIImageOrientation orientation = UIImageOrientationUp; 78 | switch (exifOrientation) { 79 | case 1: 80 | orientation = UIImageOrientationUp; 81 | break; 82 | 83 | case 3: 84 | orientation = UIImageOrientationDown; 85 | break; 86 | 87 | case 8: 88 | orientation = UIImageOrientationLeft; 89 | break; 90 | 91 | case 6: 92 | orientation = UIImageOrientationRight; 93 | break; 94 | 95 | case 2: 96 | orientation = UIImageOrientationUpMirrored; 97 | break; 98 | 99 | case 4: 100 | orientation = UIImageOrientationDownMirrored; 101 | break; 102 | 103 | case 5: 104 | orientation = UIImageOrientationLeftMirrored; 105 | break; 106 | 107 | case 7: 108 | orientation = UIImageOrientationRightMirrored; 109 | break; 110 | default: 111 | break; 112 | } 113 | return orientation; 114 | } 115 | 116 | 117 | 118 | @end 119 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 retrieved from the local cache or from the network. 47 | * The fourth 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 retrieved from the local cache or from the network. 62 | * The fourth 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 retrieved from the local cache or from the network. 78 | * The fourth 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 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 __typeof(self)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 && (options & SDWebImageAvoidAutoSetImage) && completedBlock) 43 | { 44 | completedBlock(image, error, cacheType, url); 45 | return; 46 | } 47 | else if (image) { 48 | wself.highlightedImage = image; 49 | [wself setNeedsLayout]; 50 | } 51 | if (completedBlock && finished) { 52 | completedBlock(image, error, cacheType, url); 53 | } 54 | }); 55 | }]; 56 | [self sd_setImageLoadOperation:operation forKey:UIImageViewHighlightedWebCacheOperationKey]; 57 | } else { 58 | dispatch_main_async_safe(^{ 59 | NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 60 | if (completedBlock) { 61 | completedBlock(nil, error, SDImageCacheTypeNone, url); 62 | } 63 | }); 64 | } 65 | } 66 | 67 | - (void)sd_cancelCurrentHighlightedImageLoad { 68 | [self sd_cancelImageLoadOperationWithKey:UIImageViewHighlightedWebCacheOperationKey]; 69 | } 70 | 71 | @end 72 | 73 | 74 | @implementation UIImageView (HighlightedWebCacheDeprecated) 75 | 76 | - (void)setHighlightedImageWithURL:(NSURL *)url { 77 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; 78 | } 79 | 80 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options { 81 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; 82 | } 83 | 84 | - (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock { 85 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 86 | if (completedBlock) { 87 | completedBlock(image, error, cacheType); 88 | } 89 | }]; 90 | } 91 | 92 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { 93 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 94 | if (completedBlock) { 95 | completedBlock(image, error, cacheType); 96 | } 97 | }]; 98 | } 99 | 100 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock { 101 | [self sd_setHighlightedImageWithURL:url options:0 progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 102 | if (completedBlock) { 103 | completedBlock(image, error, cacheType); 104 | } 105 | }]; 106 | } 107 | 108 | - (void)cancelCurrentHighlightedImageLoad { 109 | [self sd_cancelCurrentHighlightedImageLoad]; 110 | } 111 | 112 | @end 113 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 retrieved from the local cache or from the network. 96 | * The fourth 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 retrieved from the local cache or from the network. 111 | * The fourth 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 retrieved from the local cache or from the network. 127 | * The fourth 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 retrieved from the local cache or from the network. 144 | * The fourth 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 optionally a 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 retrieved from the local cache or from the network. 161 | * The fourth parameter is the original image url. 162 | */ 163 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url placeholderImage:(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 | /** 180 | * Show activity UIActivityIndicatorView 181 | */ 182 | - (void)setShowActivityIndicatorView:(BOOL)show; 183 | 184 | /** 185 | * set desired UIActivityIndicatorViewStyle 186 | * 187 | * @param style The style of the UIActivityIndicatorView 188 | */ 189 | - (void)setIndicatorStyle:(UIActivityIndicatorViewStyle)style; 190 | 191 | @end 192 | 193 | 194 | @interface UIImageView (WebCacheDeprecated) 195 | 196 | - (NSURL *)imageURL __deprecated_msg("Use `sd_imageURL`"); 197 | 198 | - (void)setImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:`"); 199 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:`"); 200 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options`"); 201 | 202 | - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:completed:`"); 203 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:completed:`"); 204 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:completed:`"); 205 | - (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:`"); 206 | 207 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithPreviousCachedImageWithURL:placeholderImage:options:progress:completed:`"); 208 | 209 | - (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs __deprecated_msg("Use `sd_setAnimationImagesWithURLs:`"); 210 | 211 | - (void)cancelCurrentArrayLoad __deprecated_msg("Use `sd_cancelCurrentAnimationImagesLoad`"); 212 | 213 | - (void)cancelCurrentImageLoad __deprecated_msg("Use `sd_cancelCurrentImageLoad`"); 214 | 215 | @end 216 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | static char TAG_ACTIVITY_INDICATOR; 15 | static char TAG_ACTIVITY_STYLE; 16 | static char TAG_ACTIVITY_SHOW; 17 | 18 | @implementation UIImageView (WebCache) 19 | 20 | - (void)sd_setImageWithURL:(NSURL *)url { 21 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; 22 | } 23 | 24 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { 25 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; 26 | } 27 | 28 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 29 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; 30 | } 31 | 32 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { 33 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; 34 | } 35 | 36 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { 37 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; 38 | } 39 | 40 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 41 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; 42 | } 43 | 44 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 45 | [self sd_cancelCurrentImageLoad]; 46 | objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 47 | 48 | if (!(options & SDWebImageDelayPlaceholder)) { 49 | dispatch_main_async_safe(^{ 50 | self.image = placeholder; 51 | }); 52 | } 53 | 54 | if (url) { 55 | 56 | // check if activityView is enabled or not 57 | if ([self showActivityIndicatorView]) { 58 | [self addActivityIndicator]; 59 | } 60 | 61 | __weak __typeof(self)wself = self; 62 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 63 | [wself removeActivityIndicator]; 64 | if (!wself) return; 65 | dispatch_main_sync_safe(^{ 66 | if (!wself) return; 67 | if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock) 68 | { 69 | completedBlock(image, error, cacheType, url); 70 | return; 71 | } 72 | else if (image) { 73 | wself.image = image; 74 | [wself setNeedsLayout]; 75 | } else { 76 | if ((options & SDWebImageDelayPlaceholder)) { 77 | wself.image = placeholder; 78 | [wself setNeedsLayout]; 79 | } 80 | } 81 | if (completedBlock && finished) { 82 | completedBlock(image, error, cacheType, url); 83 | } 84 | }); 85 | }]; 86 | [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"]; 87 | } else { 88 | dispatch_main_async_safe(^{ 89 | [self removeActivityIndicator]; 90 | if (completedBlock) { 91 | NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 92 | completedBlock(nil, error, SDImageCacheTypeNone, url); 93 | } 94 | }); 95 | } 96 | } 97 | 98 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 99 | NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url]; 100 | UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key]; 101 | 102 | [self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock]; 103 | } 104 | 105 | - (NSURL *)sd_imageURL { 106 | return objc_getAssociatedObject(self, &imageURLKey); 107 | } 108 | 109 | - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { 110 | [self sd_cancelCurrentAnimationImagesLoad]; 111 | __weak __typeof(self)wself = self; 112 | 113 | NSMutableArray *operationsArray = [[NSMutableArray alloc] init]; 114 | 115 | for (NSURL *logoImageURL in arrayOfURLs) { 116 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 117 | if (!wself) return; 118 | dispatch_main_sync_safe(^{ 119 | __strong UIImageView *sself = wself; 120 | [sself stopAnimating]; 121 | if (sself && image) { 122 | NSMutableArray *currentImages = [[sself animationImages] mutableCopy]; 123 | if (!currentImages) { 124 | currentImages = [[NSMutableArray alloc] init]; 125 | } 126 | [currentImages addObject:image]; 127 | 128 | sself.animationImages = currentImages; 129 | [sself setNeedsLayout]; 130 | } 131 | [sself startAnimating]; 132 | }); 133 | }]; 134 | [operationsArray addObject:operation]; 135 | } 136 | 137 | [self sd_setImageLoadOperation:[NSArray arrayWithArray:operationsArray] forKey:@"UIImageViewAnimationImages"]; 138 | } 139 | 140 | - (void)sd_cancelCurrentImageLoad { 141 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"]; 142 | } 143 | 144 | - (void)sd_cancelCurrentAnimationImagesLoad { 145 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"]; 146 | } 147 | 148 | 149 | #pragma mark - 150 | - (UIActivityIndicatorView *)activityIndicator { 151 | return (UIActivityIndicatorView *)objc_getAssociatedObject(self, &TAG_ACTIVITY_INDICATOR); 152 | } 153 | 154 | - (void)setActivityIndicator:(UIActivityIndicatorView *)activityIndicator { 155 | objc_setAssociatedObject(self, &TAG_ACTIVITY_INDICATOR, activityIndicator, OBJC_ASSOCIATION_RETAIN); 156 | } 157 | 158 | - (void)setShowActivityIndicatorView:(BOOL)show{ 159 | objc_setAssociatedObject(self, &TAG_ACTIVITY_SHOW, [NSNumber numberWithBool:show], OBJC_ASSOCIATION_RETAIN); 160 | } 161 | 162 | - (BOOL)showActivityIndicatorView{ 163 | return [objc_getAssociatedObject(self, &TAG_ACTIVITY_SHOW) boolValue]; 164 | } 165 | 166 | - (void)setIndicatorStyle:(UIActivityIndicatorViewStyle)style{ 167 | objc_setAssociatedObject(self, &TAG_ACTIVITY_STYLE, [NSNumber numberWithInt:style], OBJC_ASSOCIATION_RETAIN); 168 | } 169 | 170 | - (int)getIndicatorStyle{ 171 | return [objc_getAssociatedObject(self, &TAG_ACTIVITY_STYLE) intValue]; 172 | } 173 | 174 | - (void)addActivityIndicator { 175 | if (!self.activityIndicator) { 176 | self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:[self getIndicatorStyle]]; 177 | self.activityIndicator.translatesAutoresizingMaskIntoConstraints = NO; 178 | 179 | dispatch_main_async_safe(^{ 180 | [self addSubview:self.activityIndicator]; 181 | 182 | [self addConstraint:[NSLayoutConstraint constraintWithItem:self.activityIndicator 183 | attribute:NSLayoutAttributeCenterX 184 | relatedBy:NSLayoutRelationEqual 185 | toItem:self 186 | attribute:NSLayoutAttributeCenterX 187 | multiplier:1.0 188 | constant:0.0]]; 189 | [self addConstraint:[NSLayoutConstraint constraintWithItem:self.activityIndicator 190 | attribute:NSLayoutAttributeCenterY 191 | relatedBy:NSLayoutRelationEqual 192 | toItem:self 193 | attribute:NSLayoutAttributeCenterY 194 | multiplier:1.0 195 | constant:0.0]]; 196 | }); 197 | } 198 | 199 | dispatch_main_async_safe(^{ 200 | [self.activityIndicator startAnimating]; 201 | }); 202 | 203 | } 204 | 205 | - (void)removeActivityIndicator { 206 | if (self.activityIndicator) { 207 | [self.activityIndicator removeFromSuperview]; 208 | self.activityIndicator = nil; 209 | } 210 | } 211 | 212 | @end 213 | 214 | 215 | @implementation UIImageView (WebCacheDeprecated) 216 | 217 | - (NSURL *)imageURL { 218 | return [self sd_imageURL]; 219 | } 220 | 221 | - (void)setImageWithURL:(NSURL *)url { 222 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; 223 | } 224 | 225 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { 226 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; 227 | } 228 | 229 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 230 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; 231 | } 232 | 233 | - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock { 234 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 235 | if (completedBlock) { 236 | completedBlock(image, error, cacheType); 237 | } 238 | }]; 239 | } 240 | 241 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { 242 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 243 | if (completedBlock) { 244 | completedBlock(image, error, cacheType); 245 | } 246 | }]; 247 | } 248 | 249 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { 250 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 251 | if (completedBlock) { 252 | completedBlock(image, error, cacheType); 253 | } 254 | }]; 255 | } 256 | 257 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock { 258 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 259 | if (completedBlock) { 260 | completedBlock(image, error, cacheType); 261 | } 262 | }]; 263 | } 264 | 265 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 266 | [self sd_setImageWithPreviousCachedImageWithURL:url placeholderImage:placeholder options:options progress:progressBlock completed:completedBlock]; 267 | } 268 | 269 | - (void)cancelCurrentArrayLoad { 270 | [self sd_cancelCurrentAnimationImagesLoad]; 271 | } 272 | 273 | - (void)cancelCurrentImageLoad { 274 | [self sd_cancelCurrentImageLoad]; 275 | } 276 | 277 | - (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { 278 | [self sd_setAnimationImagesWithURLs:arrayOfURLs]; 279 | } 280 | 281 | @end 282 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/SDWebImage/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 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // MusicPlay 4 | // 5 | // Created by yedexiong on 16/11/3. 6 | // Copyright © 2016年 yoke121. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : UIViewController 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // MusicPlay 4 | // 5 | // Created by yedexiong on 16/11/3. 6 | // Copyright © 2016年 yoke121. All rights reserved. 7 | // 8 | 9 | #import "ViewController.h" 10 | #import "MusicModel.h" 11 | #import "UIImageView+WebCache.h" 12 | #import 13 | #import 14 | 15 | @interface ViewController () 16 | //音乐名 17 | @property (weak, nonatomic) IBOutlet UILabel *musicName; 18 | //演唱者 19 | @property (weak, nonatomic) IBOutlet UILabel *artist; 20 | //音乐图片 21 | @property (weak, nonatomic) IBOutlet UIImageView *musicIcon; 22 | //当前播放时间 23 | @property (weak, nonatomic) IBOutlet UILabel *currentTime; 24 | //音乐时常 25 | @property (weak, nonatomic) IBOutlet UILabel *duration; 26 | 27 | @property (weak, nonatomic) IBOutlet UIButton *playBtn; 28 | //缓冲进度条 29 | @property (weak, nonatomic) IBOutlet UIProgressView *loadTimeProgress; 30 | //播放进度滑块 31 | @property (weak, nonatomic) IBOutlet UISlider *playSlider; 32 | //数据源 33 | @property(nonatomic,strong) NSMutableArray *dataSource; 34 | //播放器 35 | @property(nonatomic,strong) AVPlayer *player; 36 | 37 | //当前播放音乐的索引 38 | @property(nonatomic,assign) NSInteger currentIndex; 39 | //当前播放的音乐模型 40 | @property(nonatomic,strong) MusicModel *currentModel; 41 | 42 | //缓存音乐图片 43 | @property(nonatomic,strong) NSMutableDictionary *musicImageDic; 44 | 45 | //当前歌曲进度监听者 46 | @property(nonatomic,strong) id timeObserver; 47 | 48 | @end 49 | 50 | @implementation ViewController 51 | 52 | - (void)viewDidLoad { 53 | 54 | [super viewDidLoad]; 55 | 56 | [self loadData]; 57 | 58 | self.currentIndex = 0; 59 | [self playBtnAction:self.playBtn]; 60 | 61 | } 62 | 63 | #pragma mark - private 64 | -(void)loadData 65 | { 66 | NSString *path = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"json"]; 67 | NSData *data = [NSData dataWithContentsOfFile:path]; 68 | NSArray *datas = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 69 | for (NSDictionary *dic in datas) { 70 | 71 | MusicModel *model = [[MusicModel alloc] initWithDic:dic]; 72 | [self.dataSource addObject:model]; 73 | 74 | } 75 | } 76 | 77 | -(void)reloadUI:(MusicModel*)model 78 | { 79 | self.musicName.text = model.name; 80 | self.artist.text = model.artist; 81 | [self.musicIcon sd_setImageWithURL:[NSURL URLWithString:model.cover]]; 82 | self.duration.text = model.duration; 83 | self.playBtn.selected = YES; 84 | self.playSlider.value = 0; 85 | self.loadTimeProgress.progress = 0; 86 | 87 | } 88 | 89 | #pragma mark- 音乐播放相关 90 | //播放音乐 91 | -(void)playWithUrl:(MusicModel*)model 92 | { 93 | AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:model.url]]; 94 | 95 | //替换当前音乐资源 96 | [self.player replaceCurrentItemWithPlayerItem:item]; 97 | 98 | //刷新界面UI 99 | [self reloadUI:model]; 100 | 101 | //监听音乐播放完成通知 102 | [self addNSNotificationForPlayMusicFinish]; 103 | 104 | //开始播放 105 | [self.player play]; 106 | 107 | //监听播放器状态 108 | [self addPlayStatus]; 109 | 110 | //监听音乐缓冲进度 111 | [self addPlayLoadTime]; 112 | 113 | //监听音乐播放的进度 114 | [self addMusicProgressWithItem:item]; 115 | 116 | //记录当前播放音乐的索引 117 | self.currentIndex = [model.Id integerValue]; 118 | self.currentModel = model; 119 | 120 | //音乐锁屏信息展示 121 | [self setupLockScreenInfo]; 122 | 123 | } 124 | 125 | 126 | #pragma mark - 设置锁屏信息 127 | 128 | //音乐锁屏信息展示 129 | - (void)setupLockScreenInfo 130 | { 131 | // 1.获取锁屏中心 132 | MPNowPlayingInfoCenter *playingInfoCenter = [MPNowPlayingInfoCenter defaultCenter]; 133 | 134 | //初始化一个存放音乐信息的字典 135 | NSMutableDictionary *playingInfoDict = [NSMutableDictionary dictionary]; 136 | // 2、设置歌曲名 137 | if (self.currentModel.name) { 138 | [playingInfoDict setObject:self.currentModel.name forKey:MPMediaItemPropertyAlbumTitle]; 139 | } 140 | // 设置歌手名 141 | if (self.currentModel.artist) { 142 | [playingInfoDict setObject:self.currentModel.artist forKey:MPMediaItemPropertyArtist]; 143 | } 144 | // 3设置封面的图片 145 | UIImage *image = [self getMusicImageWithMusicId:self.currentModel]; 146 | if (image) { 147 | MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image]; 148 | [playingInfoDict setObject:artwork forKey:MPMediaItemPropertyArtwork]; 149 | } 150 | 151 | // 4设置歌曲的总时长 152 | [playingInfoDict setObject:self.currentModel.detailDuration forKey:MPMediaItemPropertyPlaybackDuration]; 153 | 154 | //音乐信息赋值给获取锁屏中心的nowPlayingInfo属性 155 | playingInfoCenter.nowPlayingInfo = playingInfoDict; 156 | 157 | // 5.开启远程交互 158 | [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; 159 | } 160 | 161 | //获取远程网络图片,如有缓存取缓存,没有缓存,远程加载并缓存 162 | -(UIImage*)getMusicImageWithMusicId:(MusicModel*)model 163 | { 164 | UIImage *image; 165 | NSString *key = [model.Id stringValue]; 166 | UIImage *cacheImage = self.musicImageDic[key]; 167 | if (cacheImage) { 168 | image = cacheImage; 169 | }else{ 170 | //这里用了非常规的做法,仅用于demo快速测试,实际开发不推荐,会堵塞主线程 171 | //建议加载歌曲时先把网络图片请求下来再设置 172 | NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:model.cover]]; 173 | image = [UIImage imageWithData:data]; 174 | if (image) { 175 | [self.musicImageDic setObject:image forKey:key]; 176 | 177 | } 178 | } 179 | 180 | return image; 181 | } 182 | 183 | 184 | //监听远程交互方法 185 | - (void)remoteControlReceivedWithEvent:(UIEvent *)event 186 | { 187 | 188 | switch (event.subtype) { 189 | //播放 190 | case UIEventSubtypeRemoteControlPlay:{ 191 | [self.player play]; 192 | } 193 | break; 194 | //停止 195 | case UIEventSubtypeRemoteControlPause:{ 196 | [self.player pause]; 197 | } 198 | break; 199 | //下一首 200 | case UIEventSubtypeRemoteControlNextTrack: 201 | [self nextBtnAction:nil]; 202 | break; 203 | //上一首 204 | case UIEventSubtypeRemoteControlPreviousTrack: 205 | [self lastBtnAction:nil]; 206 | break; 207 | 208 | default: 209 | break; 210 | } 211 | } 212 | 213 | #pragma mark - NSNotification 214 | -(void)addNSNotificationForPlayMusicFinish 215 | { 216 | [[NSNotificationCenter defaultCenter] removeObserver:self]; 217 | //给AVPlayerItem添加播放完成通知 218 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:_player.currentItem]; 219 | } 220 | 221 | -(void)playFinished:(NSNotification*)notification 222 | { 223 | //播放下一首 224 | [self nextBtnAction:nil]; 225 | } 226 | 227 | 228 | 229 | #pragma mark - 监听音乐各种状态 230 | //通过KVO监听播放器状态 231 | -(void)addPlayStatus 232 | { 233 | 234 | [self.player.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil]; 235 | 236 | } 237 | //移除监听播放器状态 238 | -(void)removePlayStatus 239 | { 240 | if (self.currentModel == nil) {return;} 241 | 242 | [self.player.currentItem removeObserver:self forKeyPath:@"status"]; 243 | } 244 | 245 | 246 | 247 | //KVO监听音乐缓冲状态 248 | -(void)addPlayLoadTime 249 | { 250 | [self.player.currentItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil]; 251 | 252 | } 253 | //移除监听音乐缓冲状态 254 | -(void)removePlayLoadTime 255 | { 256 | if (self.currentModel == nil) {return;} 257 | [self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"]; 258 | } 259 | 260 | //监听音乐播放的进度 261 | -(void)addMusicProgressWithItem:(AVPlayerItem *)item 262 | { 263 | //移除监听音乐播放进度 264 | [self removeTimeObserver]; 265 | __weak typeof(self) weakSelf = self; 266 | self.timeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) { 267 | //当前播放的时间 268 | float current = CMTimeGetSeconds(time); 269 | //总时间 270 | float total = CMTimeGetSeconds(item.duration); 271 | if (current) { 272 | float progress = current / total; 273 | //更新播放进度条 274 | weakSelf.playSlider.value = progress; 275 | weakSelf.currentTime.text = [weakSelf timeFormatted:current]; 276 | } 277 | }]; 278 | 279 | } 280 | 281 | //转换成时分秒 282 | - (NSString *)timeFormatted:(int)totalSeconds 283 | { 284 | int seconds = totalSeconds % 60; 285 | int minutes = (totalSeconds / 60) % 60; 286 | 287 | return [NSString stringWithFormat:@"%02d:%02d",minutes, seconds]; 288 | } 289 | //移除监听音乐播放进度 290 | -(void)removeTimeObserver 291 | { 292 | if (self.timeObserver) { 293 | [self.player removeTimeObserver:self.timeObserver]; 294 | self.timeObserver = nil; 295 | } 296 | } 297 | 298 | //观察者回调 299 | -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 300 | 301 | { 302 | if ([keyPath isEqualToString:@"status"]) { 303 | switch (self.player.status) { 304 | case AVPlayerStatusUnknown: 305 | { 306 | NSLog(@"未知转态"); 307 | } 308 | break; 309 | case AVPlayerStatusReadyToPlay: 310 | { 311 | NSLog(@"准备播放"); 312 | } 313 | break; 314 | case AVPlayerStatusFailed: 315 | { 316 | NSLog(@"加载失败"); 317 | } 318 | break; 319 | 320 | default: 321 | break; 322 | } 323 | 324 | } 325 | 326 | if ([keyPath isEqualToString:@"loadedTimeRanges"]) { 327 | 328 | NSArray * timeRanges = self.player.currentItem.loadedTimeRanges; 329 | //本次缓冲的时间范围 330 | CMTimeRange timeRange = [timeRanges.firstObject CMTimeRangeValue]; 331 | //缓冲总长度 332 | NSTimeInterval totalLoadTime = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration); 333 | //音乐的总时间 334 | NSTimeInterval duration = CMTimeGetSeconds(self.player.currentItem.duration); 335 | //计算缓冲百分比例 336 | NSTimeInterval scale = totalLoadTime/duration; 337 | //更新缓冲进度条 338 | self.loadTimeProgress.progress = scale; 339 | } 340 | } 341 | 342 | 343 | #pragma mark - action 344 | //播放上一首 345 | - (IBAction)lastBtnAction:(UIButton *)sender 346 | { 347 | //取出下一首音乐模型 348 | if (self.currentIndex - 1 < 0) { 349 | self.currentIndex = self.dataSource.count -1; 350 | }else{ 351 | self.currentIndex -= 1; 352 | } 353 | [self removePlayStatus]; 354 | [self removePlayLoadTime]; 355 | MusicModel *model = self.dataSource[self.currentIndex]; 356 | [self playWithUrl:model]; 357 | 358 | } 359 | 360 | //播放 361 | - (IBAction)playBtnAction:(UIButton *)sender 362 | { 363 | if (!sender.selected) { 364 | [self playWithUrl:self.dataSource[self.currentIndex]]; 365 | sender.selected = YES; 366 | }else{ 367 | [self.player pause]; 368 | [self removePlayStatus]; 369 | [self removePlayLoadTime]; 370 | self.currentModel = nil; 371 | sender.selected = NO; 372 | } 373 | 374 | } 375 | //下一首 376 | - (IBAction)nextBtnAction:(UIButton *)sender { 377 | //取出下一首音乐模型 378 | if (self.currentIndex +1 > self.dataSource.count -1) { 379 | self.currentIndex = 0; 380 | }else{ 381 | self.currentIndex += 1; 382 | } 383 | [self removePlayStatus]; 384 | [self removePlayLoadTime]; 385 | MusicModel *model = self.dataSource[self.currentIndex]; 386 | [self playWithUrl:model]; 387 | 388 | } 389 | //移动滑块调整播放进度 390 | - (IBAction)playSliderValueChange:(UISlider *)sender 391 | { 392 | //根据值计算时间 393 | float time = sender.value * CMTimeGetSeconds(self.player.currentItem.duration); 394 | //跳转到当前指定时间 395 | [self.player seekToTime:CMTimeMake(time, 1)]; 396 | } 397 | 398 | 399 | #pragma mark - getter 400 | -(NSMutableArray *)dataSource 401 | { 402 | if (_dataSource == nil) { 403 | _dataSource = [NSMutableArray array]; 404 | } 405 | return _dataSource; 406 | } 407 | -(AVPlayer *)player 408 | { 409 | if (_player == nil) { 410 | //初始化_player 411 | AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:@""]]; 412 | _player = [[AVPlayer alloc] initWithPlayerItem:item]; 413 | } 414 | 415 | return _player; 416 | } 417 | 418 | 419 | -(NSMutableDictionary *)musicImageDic 420 | { 421 | if (_musicImageDic == nil) { 422 | _musicImageDic = [NSMutableDictionary dictionary]; 423 | } 424 | return _musicImageDic; 425 | } 426 | 427 | 428 | 429 | 430 | 431 | @end 432 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // MusicPlay 4 | // 5 | // Created by yedexiong on 16/11/3. 6 | // Copyright © 2016年 yoke121. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "AppDelegate.h" 11 | 12 | int main(int argc, char * argv[]) { 13 | @autoreleasepool { 14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlay/music.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "id": 0, 3 | "name": "Adagio sostenuto", 4 | "artist": "Ludwig van Beethoven", 5 | "cover": "http:\/\/download.lingyongqian.cn\/music\/ViolinConcertoOp61InDMajorII.jpg", 6 | "duration": "07:05", 7 | "url": "http:\/\/download.lingyongqian.cn\/music\/AdagioSostenuto.mp3" 8 | }, { 9 | "id": 1, 10 | "name": "For Elise", 11 | "artist": "Ludwig van Beethoven", 12 | "cover": "http:\/\/download.lingyongqian.cn\/music\/ForElise.jpg", 13 | "duration": "02:57", 14 | "url": "http:\/\/download.lingyongqian.cn\/music\/ForElise.mp3" 15 | }, { 16 | "id": 2, 17 | "name": "Minuet in G", 18 | "artist": "Ludwig van Beethoven", 19 | "cover": "http:\/\/download.lingyongqian.cn\/music\/MinuetInG.jpg", 20 | "duration": "02:55", 21 | "url": "http:\/\/download.lingyongqian.cn\/music\/MinuetInG.mp3" 22 | }, { 23 | "id": 3, 24 | "name": "Moonlight Sonata", 25 | "artist": "Ludwig van Beethoven", 26 | "cover": "http:\/\/download.lingyongqian.cn\/music\/MoonlightSonata.jpg", 27 | "duration": "03:32", 28 | "url": "http:\/\/download.lingyongqian.cn\/music\/MoonlightSonata.mp3" 29 | }, { 30 | "id": 4, 31 | "name": "Rondo.Allegro", 32 | "artist": "Ludwig van Beethoven", 33 | "cover": "http:\/\/download.lingyongqian.cn\/music\/RondoAllegro.jpg", 34 | "duration": "04:47", 35 | "url": "http:\/\/download.lingyongqian.cn\/music\/RondoAllegro.mp3" 36 | }, { 37 | "id": 5, 38 | "name": "Violin Concerto op 61 in D major I", 39 | "artist": "Ludwig van Beethoven", 40 | "cover": "http:\/\/download.lingyongqian.cn\/music\/ViolinConcertoOp61InDMajorI.jpg", 41 | "duration": "24:29", 42 | "url": "http:\/\/download.lingyongqian.cn\/music\/ViolinConcertoOp61InDMajorI.mp3" 43 | }, { 44 | "id": 6, 45 | "name": "Violin Concerto op 61 in D major II", 46 | "artist": "Ludwig van Beethoven", 47 | "cover": "http:\/\/download.lingyongqian.cn\/music\/ViolinConcertoOp61InDMajorII.jpg", 48 | "duration": "24:29", 49 | "url": "http:\/\/download.lingyongqian.cn\/music\/ViolinConcertoOp61InDMajorII.mp3" 50 | }, { 51 | "id": 7, 52 | "name": "Violin Concerto op 61 in D major III", 53 | "artist": "Ludwig van Beethoven", 54 | "cover": "http:\/\/download.lingyongqian.cn\/music\/ViolinConcertoOp61InDMajorIII.jpg", 55 | "duration": "24:29", 56 | "url": "http:\/\/download.lingyongqian.cn\/music\/ViolinConcertoOp61InDMajorIII.mp3" 57 | }] 58 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlayTests/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 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlayTests/MusicPlayTests.m: -------------------------------------------------------------------------------- 1 | // 2 | // MusicPlayTests.m 3 | // MusicPlayTests 4 | // 5 | // Created by yedexiong on 16/11/3. 6 | // Copyright © 2016年 yoke121. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface MusicPlayTests : XCTestCase 12 | 13 | @end 14 | 15 | @implementation MusicPlayTests 16 | 17 | - (void)setUp { 18 | [super setUp]; 19 | // Put setup code here. This method is called before the invocation of each test method in the class. 20 | } 21 | 22 | - (void)tearDown { 23 | // Put teardown code here. This method is called after the invocation of each test method in the class. 24 | [super tearDown]; 25 | } 26 | 27 | - (void)testExample { 28 | // This is an example of a functional test case. 29 | // Use XCTAssert and related functions to verify your tests produce the correct results. 30 | } 31 | 32 | - (void)testPerformanceExample { 33 | // This is an example of a performance test case. 34 | [self measureBlock:^{ 35 | // Put the code you want to measure the time of here. 36 | }]; 37 | } 38 | 39 | @end 40 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlayUITests/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 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /MusicPlay/MusicPlayUITests/MusicPlayUITests.m: -------------------------------------------------------------------------------- 1 | // 2 | // MusicPlayUITests.m 3 | // MusicPlayUITests 4 | // 5 | // Created by yedexiong on 16/11/3. 6 | // Copyright © 2016年 yoke121. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface MusicPlayUITests : XCTestCase 12 | 13 | @end 14 | 15 | @implementation MusicPlayUITests 16 | 17 | - (void)setUp { 18 | [super setUp]; 19 | 20 | // Put setup code here. This method is called before the invocation of each test method in the class. 21 | 22 | // In UI tests it is usually best to stop immediately when a failure occurs. 23 | self.continueAfterFailure = NO; 24 | // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. 25 | [[[XCUIApplication alloc] init] launch]; 26 | 27 | // 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. 28 | } 29 | 30 | - (void)tearDown { 31 | // Put teardown code here. This method is called after the invocation of each test method in the class. 32 | [super tearDown]; 33 | } 34 | 35 | - (void)testExample { 36 | // Use recording to get started writing UI tests. 37 | // Use XCTAssert and related functions to verify your tests produce the correct results. 38 | } 39 | 40 | @end 41 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MsuicPlayDemo 2 | 一款播放网略音乐的demo 3 | --------------------------------------------------------------------------------