Browse Source

Prefer to use KF based APIs

onevcat 5 years ago
parent
commit
c18b4c6068

+ 8 - 4
Demo/Demo/Kingfisher-Demo/Base.lproj/Main.storyboard

@@ -1,9 +1,9 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17147" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="peg-r0-mlo">
+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17156" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="peg-r0-mlo">
     <device id="retina5_5" orientation="portrait" appearance="dark"/>
     <dependencies>
         <deployment identifier="iOS"/>
-        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17120"/>
+        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17125"/>
         <capability name="Safe area layout guides" minToolsVersion="9.0"/>
         <capability name="System colors in document resources" minToolsVersion="11.0"/>
         <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
@@ -466,8 +466,12 @@
                         <rect key="frame" x="0.0" y="0.0" width="414" height="736"/>
                         <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                         <subviews>
-                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="YVS-ul-f2n">
-                                <rect key="frame" x="186" y="379.66666666666669" width="42" height="21"/>
+                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="YVS-ul-f2n">
+                                <rect key="frame" x="82" y="365" width="250" height="50"/>
+                                <constraints>
+                                    <constraint firstAttribute="width" relation="greaterThanOrEqual" constant="250" id="hkg-9V-168"/>
+                                    <constraint firstAttribute="height" constant="50" id="oop-I0-zGm"/>
+                                </constraints>
                                 <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                 <nil key="textColor"/>
                                 <nil key="highlightedColor"/>

+ 1 - 4
Demo/Demo/Kingfisher-Demo/ViewControllers/AVAssetImageGeneratorViewController.swift

@@ -38,9 +38,6 @@ class AVAssetImageGeneratorViewController: UIViewController {
             assetURL: URL(string: "https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_1280_10MG.mp4")!,
             seconds: 15.0
         )
-
-        imageView.kf.setImage(with: provider) { r in
-            print(r)
-        }
+        KF.dataProvider(provider).set(to: imageView)
     }
 }

+ 2 - 5
Demo/Demo/Kingfisher-Demo/ViewControllers/GIFViewController.swift

@@ -37,11 +37,8 @@ class GIFViewController: UIViewController {
         let url = ImageLoader.gifImageURLs.last!
         
         // Should need to use different cache key to prevent data overwritten by each other.
+        KF.url(url, cacheKey: "\(url)-imageview").set(to: imageView)
         
-        let imageViewResource = ImageResource(downloadURL: url, cacheKey: "\(url)-imageview")
-        imageView.kf.setImage(with: imageViewResource)
-        
-        let animatedImageViewResource = ImageResource(downloadURL: url, cacheKey: "\(url)-animated_imageview")
-        animatedImageView.kf.setImage(with: animatedImageViewResource)
+        KF.url(url, cacheKey: "\(url)-animated_imageview").set(to: animatedImageView)
     }
 }

+ 6 - 9
Demo/Demo/Kingfisher-Demo/ViewControllers/HighResolutionCollectionViewController.swift

@@ -60,19 +60,16 @@ class HighResolutionCollectionViewController: UICollectionViewController {
         let url = ImageLoader.highResolutionImageURLs[indexPath.row % ImageLoader.highResolutionImageURLs.count]
         // Use different cache key to prevent reuse the same image. It is just for
         // this demo. Normally you can just use the URL to set image.
-        let resource = ImageResource(downloadURL: url, cacheKey: "\(url.absoluteString)-\(indexPath.row)")
-        
+
         // This should crash most devices due to memory pressure.
+        // let resource = ImageResource(downloadURL: url, cacheKey: "\(url.absoluteString)-\(indexPath.row)")
         // imageView.kf.setImage(with: resource)
 
         // This would survive on even the lowest spec devices!
-        imageView.kf.setImage(
-            with: resource,
-            options: [
-                .processor(DownsamplingImageProcessor(size: CGSize(width: 250, height: 250))),
-                .cacheOriginalImage
-            ]
-        )
+        KF.url(url, cacheKey: "\(url.absoluteString)-\(indexPath.row)")
+            .downsampling(size: CGSize(width: 250, height: 250))
+            .cacheOriginalImage()
+            .set(to: imageView)
     }
     
     override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

+ 3 - 1
Demo/Demo/Kingfisher-Demo/ViewControllers/ImageDataProviderCollectionViewController.swift

@@ -50,7 +50,9 @@ class ImageDataProviderCollectionViewController: UICollectionViewController {
     
         let pair = model[indexPath.row]
         let provider = UserNameLetterIconImageProvider(userNameFirstLetter: pair.0, backgroundColor: pair.1)
-        cell.cellImageView.kf.setImage(with: provider, options:[.processor(RoundCornerImageProcessor(cornerRadius: 75))])
+        KF.dataProvider(provider)
+            .roundCorner(point: 75)
+            .set(to: cell.cellImageView)
 
         return cell
     }

+ 4 - 3
Demo/Demo/Kingfisher-Demo/ViewControllers/IndicatorCollectionViewController.swift

@@ -100,9 +100,10 @@ class IndicatorCollectionViewController: UICollectionViewController {
     override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
         let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImageCollectionViewCell
         cell.cellImageView.kf.indicatorType = selectedIndicatorType
-        cell.cellImageView.kf.setImage(
-            with: ImageLoader.sampleImageURLs[indexPath.row],
-            options: [.memoryCacheExpiration(.expired), .diskCacheExpiration(.expired)])
+        KF.url(ImageLoader.sampleImageURLs[indexPath.row])
+            .memoryCacheExpiration(.expired)
+            .diskCacheExpiration(.expired)
+            .set(to: cell.cellImageView)
         return cell
     }
     

+ 1 - 1
Demo/Demo/Kingfisher-Demo/ViewControllers/InfinityCollectionViewController.swift

@@ -53,7 +53,7 @@ class InfinityCollectionViewController: UICollectionViewController {
 
         // Mark each row as a new image.
         let resource = ImageResource(downloadURL: url, cacheKey: "key-\(indexPath.row)")
-        cell.cellImageView.kf.setImage(with: resource)
+        KF.resource(resource).set(to: cell.cellImageView)
 
         return cell
     }

+ 8 - 7
Demo/Demo/Kingfisher-Demo/ViewControllers/ProcessorCollectionViewController.swift

@@ -70,13 +70,14 @@ class ProcessorCollectionViewController: UICollectionViewController {
     override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
         let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImageCollectionViewCell
         let url = ImageLoader.sampleImageURLs[indexPath.row]
-        var options: KingfisherOptionsInfo = [.processor(currentProcessor)]
-        if currentProcessor is RoundCornerImageProcessor {
-            options.append(.cacheSerializer(FormatIndicatedCacheSerializer.png))
-        }
-        cell.cellImageView.kf.setImage(with: url, options: options) { result in
-            print(result)
-        }
+
+        KF.url(url)
+            .setProcessor(currentProcessor)
+            .serialize(as: .PNG)
+            .done { print($0) }
+            .catch { print($0) }
+            .set(to: cell.cellImageView)
+
         return cell
     }
     

+ 15 - 19
Demo/Demo/Kingfisher-Demo/ViewControllers/ProgressiveJPEGViewController.swift

@@ -52,28 +52,24 @@ class ProgressiveJPEGViewController: UIViewController {
             isFastestScan: isFastestScan,
             scanInterval: 0.1
         )
-        
-        imageView.kf.setImage(
-            with: ImageLoader.progressiveImageURL,
-            placeholder: nil,
-            options: [.loadDiskFileSynchronously,
-                      .progressiveJPEG(progressive),
-                      .processor(processor)],
-            progressBlock: { receivedSize, totalSize in
+
+        KF.url(ImageLoader.progressiveImageURL)
+            .loadDiskFileSynchronously()
+            .progressiveJPEG(progressive)
+            .roundCorner(point: 30)
+            .progress { receivedSize, totalSize in
                 print("\(receivedSize)/\(totalSize)")
                 self.progressLabel.text = "\(receivedSize) / \(totalSize)"
-            },
-            completionHandler: { result in
-                do {
-                    let value = try result.get()
-                    print(value)
-                    print("Finished")
-                    
-                } catch {
-                    self.progressLabel.text = error.localizedDescription
-                }
             }
-        )
+            .done { result in
+                print(result)
+                print("Finished")
+            }
+            .catch { error in
+                print(error)
+                self.progressLabel.text = error.localizedDescription
+            }
+            .set(to: imageView)
     }
     
     override func alertPopup(_ sender: Any) -> UIAlertController {

+ 5 - 9
Demo/Demo/Kingfisher-Demo/ViewControllers/TextAttachmentViewController.swift

@@ -43,17 +43,13 @@ class TextAttachmentViewController: UIViewController {
         let attributedText = NSMutableAttributedString(string: "Hello World")
 
         let textAttachment = NSTextAttachment()
-        textAttachment.kf.setImage(
-            with: URL(string: "https://onevcat.com/assets/images/avatar.jpg")!,
-            attributedView: label,
-            options: [
-                .processor(
-                    ResizingImageProcessor(referenceSize: .init(width: 30, height: 30))
-                    |> RoundCornerImageProcessor(cornerRadius: 15))
-                ]
-        )
         attributedText.replaceCharacters(in: NSRange(), with: NSAttributedString(attachment: textAttachment))
         label.attributedText = attributedText
+
+        KF.url(URL(string: "https://onevcat.com/assets/images/avatar.jpg")!)
+            .resizing(referenceSize: CGSize(width: 30, height: 30))
+            .roundCorner(point: 15)
+            .set(to: textAttachment, attributedView: label)
     }
 }
 

+ 4 - 1
Demo/Demo/Kingfisher-Demo/ViewControllers/TransitionViewController.swift

@@ -69,7 +69,10 @@ class TransitionViewController: UIViewController {
         
         let t = makeTransition(type: transitionType, duration: duration)
         let url = ImageLoader.sampleImageURLs[0]
-        imageView.kf.setImage(with: url, options: [.forceTransition, .transition(t)])
+        KF.url(url)
+            .forceTransition()
+            .transition(t)
+            .set(to: imageView)
     }
 }
 

+ 3 - 0
Sources/Extensions/NSTextAttachment+Kingfisher.swift

@@ -224,6 +224,9 @@ extension KingfisherWrapper where Base: NSTextAttachment {
                         self.base.image = value.image
                         #if canImport(UIKit)
                         attributedView.setNeedsDisplay()
+                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
+                            
+                        }
                         #else
                         attributedView.setNeedsDisplay(attributedView.bounds)
                         #endif

+ 8 - 2
Sources/General/KF.swift

@@ -45,8 +45,8 @@ public class KF {
         Builder(source: .network(resource))
     }
 
-    public static func url(_ url: URL) -> KF.Builder {
-        Builder(source: .network(url))
+    public static func url(_ url: URL, cacheKey: String? = nil) -> KF.Builder {
+        Builder(source: .network(ImageResource(downloadURL: url, cacheKey: cacheKey)))
     }
 
     public static func dataProvider(_ provider: ImageDataProvider) -> KF.Builder {
@@ -512,6 +512,12 @@ extension KF.Builder {
             return appendProcessor(processor)
         }
     }
+
+    public func resizing(referenceSize: CGSize, mode: ContentMode = .none) -> Self {
+        appendProcessor(
+            ResizingImageProcessor(referenceSize: referenceSize, mode: mode)
+        )
+    }
 }
 
 // MARK: - Cache Serializer

+ 9 - 13
Tests/KingfisherTests/ImageViewExtensionTests.swift

@@ -166,24 +166,20 @@ class ImageViewExtensionTests: XCTestCase {
         let group = DispatchGroup()
         
         group.enter()
-        let task1 = imageView.kf.setImage(with: url) {
-            result in
-            XCTAssertNil(result.value)
-            group.leave()
-        }
+        let task1 = KF.url(url)
+            .catch { _ in group.leave() }
+            .set(to: imageView)
         
         group.enter()
-        imageView.kf.setImage(with: url) { result in
-            XCTAssertNotNil(result.value)
-            group.leave()
-        }
+        KF.url(url)
+            .done { _ in group.leave() }
+            .set(to: imageView)
         
         group.enter()
         let anotherImageView = KFCrossPlatformImageView()
-        anotherImageView.kf.setImage(with: url) { result in
-            XCTAssertNotNil(result.value)
-            group.leave()
-        }
+        KF.url(url)
+            .done { _ in group.leave() }
+            .set(to: anotherImageView)
         
         task1?.cancel()
         _ = stub.go()