0

为了从服务器获取图像,我已经这样做了

// fetch image from server
    func fetchImage(url: NSURL) -> Operation<UIImage, NSError> {
        return Operation { observer in

            // use almofire to deal with server request
            let request = Alamofire.request(.GET, url).response { request, response, data, error in

                // if error occurs then abort the operation
                if let error = error {
                    observer.failure(error)
                } else {
                    // if doesnt occurs error then convert imageData back to image
                    if(data != nil)
                    {
                        observer.next(UIImage(data : data!)!)
                        observer.success()
                    }
                }
            }

            // if response is nil then execute this block
            return BlockDisposable {
                request.cancel()
            }
        }

    }

& 然后将其绑定到图像视图

if (url != nil)
        {
            let image : ObservableBuffer<UIImage>? = self.fetchImage(url!).shareNext()

            if ((image) != nil)
            {

                image!.bindTo(customCellObj.mContentCellImageView)
            }
        }

在这里,我使用 almofire 从 url 获取图像。有什么方法可以直接使用反应套件将本地数据库图像与图像视图绑定?

4

1 回答 1

0

以下是将 imageView 连接到流的方法:

    Stream.just(NSURL(string: "https://exoticcars.enterprise.com/etc/designs/exotics/clientlibs/dist/img/homepage/Homepage-Hero-Car.png")!)
        .flatMapLatest(fetchImage)
        .flatMapError { _ in return Stream.just(UIImage()) }
        .observeNext { [weak self] image in self?.imageView.image = image }
        .disposeIn(bag)

然而,冒着听起来太明显的风险......这就是 ReactiveUIKit 的用途。

    Stream.just(NSURL(string: "https://exoticcars.enterprise.com/etc/designs/exotics/clientlibs/dist/img/homepage/Homepage-Hero-Car.png")!)
        .flatMapLatest(fetchImage)
        .flatMapError { _ in return Stream.just(UIImage()) }
        .bindTo(imageView.rImage)
        .disposeIn(bag)

还有一个 ReactiveKit (AlamofireReactive) 的 Alamofire 扩展,您可能会觉得它很有用。

于 2016-10-09T16:32:00.507 回答