How to integrate latest SDWebImage API in my Swift based project?

前端 未结 3 471
清歌不尽
清歌不尽 2021-01-04 10:46

I have used SDWebImage with Objective C and it worked great for me but now I am learning Swift and trying to integrate the latest version of the API but I am stucking at eve

3条回答
  •  我在风中等你
    2021-01-04 11:20

    The best option will be to drag and drop SDWebImage folder to project. Make sure 'copy items if needed' is ticked on.

    Make a Obj C Bridging:File -> New -> Source -> Header File -> Name as AppName-Bridging-Header.

    Add the following:

            #ifndef AppName_AppName_Bridging_Header_h
            #define AppName_AppName_Bridging_Header_h
    
            #import 
            #import "UIImageView+WebCache.h"
            #endif
    
        or
    
     #import "UIImageView+WebCache.h"   
    

    Reference: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html

    Note: Build Settings, in Swift Compiler - Code Generation, make sure the Objective-C Bridging Header build setting under has a path to the bridging header file. - its like testSD/testSD-Bridging-Header.h or testSD-Bridging-Header.h (Open the Project folder and find the header file path)

    Now try with this code:

    let block: SDWebImageCompletionBlock! = {(image: UIImage!, error: NSError!, cacheType: SDImageCacheType!, imageURL: NSURL!) -> Void in
        println(self)
    }
    
    let url = NSURL(string: "http://arrow_upward.com/350x150")
    self.imageView.sd_setImageWithURL(url, completed: block)
    

    Suppose if you are using a UICollectionView to populate Cache imaging, try with this code.

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
            let cell = photoListCollectionView.dequeueReusableCellWithReuseIdentifier("scoutimagecellidentifier", forIndexPath: indexPath) as! ScoutImageCell
    
            //Loading image from server using SDWebImage library
            let thumbImageUrl  =   NSURL(string: self.photoPropertyArray[indexPath.row] as String)
    
            //Image Fetching is done in background GCD thread        
    
    SDWebImageManager.sharedManager().downloadImageWithURL(thumbImageUrl, options: [],progress: nil, completed: {[weak self] (image, error, cached, finished, url) in
    
    if let wSelf = self {
    
                    //On Main Thread
                    dispatch_async(dispatch_get_main_queue()){
                        cell.scoutimage.image = image
                        cell.photoloader.stopAnimating()
                    }
                }
                })
            return cell
        }
    

提交回复
热议问题