图像下载问题

时间:2018-03-27 05:36:23

标签: ios objective-c nsurlconnection nsurlrequest nsurlsessiondownloadtask

我正在尝试从以下网址下载图片。收到状态代码后,200文件成功下载,但如果状态代码为301则会在Header中为我提供一个新URL,但从该URL下载失败。

第1步: https://www.lancecamper.com/images/trailers/lance-rv-trailers-1475s-din-2018.jpg

回复:

{ URL: https://www.lancecamper.com/images/trailers/lance-rv-trailers-1475s-din-2018.jpg }
{ status code: 200, headers {
    "Accept-Ranges" = bytes;
    "Cache-Control" = "public,max-age=7776000";
    "Content-Length" = 224200;
    "Content-Type" = "image/jpeg";
    Date = "Tue, 27 Mar 2018 04:52:30 GMT";
    Etag = "\"5bea410a65dd31:0\"";
    "Last-Modified" = "Wed, 15 Nov 2017 00:09:27 GMT";
    Server = "Microsoft-IIS/8.5";
    "X-Powered-By" = "ASP.NET";
}}

状态=已成功下载。

第2步:http://www.lancecamper.com/images/trailers/TT_1685_Int_hero.jpg 回复:

{ URL: http://www.lancecamper.com/images/trailers/TT_1685_Int_hero.jpg }
{ status code: 301, headers {
    "Content-Length" = 187;
    "Content-Type" = "text/html; charset=UTF-8";
    Date = "Tue, 27 Mar 2018 05:18:45 GMT";
    Location = "https://www.lancecamper.com/images/trailers/TT_1685_Int_hero.jpg";
    Server = "Microsoft-IIS/8.5";
    "X-Powered-By" = "ASP.NET";
}}

当我获得状态301时,我还会在“位置”标题中获取新网址,但我无法使用该网址下载该文件。它显示了成功状态,但告诉我不支持格式。它在android中工作,我不知道为什么。

状态=已成功下载但未支持图片格式。

2 个答案:

答案 0 :(得分:0)

@ilesh尝试使用此UIImageView扩展方法:

// Download image with given URL and Placeholder image is used when downloading failed.
public func imageFromURL(string: String?, placeholderImageName: String?, completion: ((Bool) -> Void)?) {
    if let placeholderImageName = placeholderImageName {
        self.image = UIImage(named: placeholderImageName)
    }
    else {
        self.image = nil
    }

    //Set unique identifier to check re-usability condition
    let strUniqueIdentifier = "\(abs(string?.hashValue ?? (UUID().uuidString.hashValue)))"
    if self.accessibilityLabel != strUniqueIdentifier {
        if let request = self.accessibilityElements?.first as? DataRequest {
            //A download task is already in progress so cancel it
            request.cancel()
            self.accessibilityElements?.removeAll()
        }
    }
    self.accessibilityLabel = strUniqueIdentifier

    guard let url = URL(string: string?.replacingOccurrences(of: " ", with: "%20") ?? "")
        else {
            print("\(#function)No url specified")

            if let completion = completion {
                completion(false)
            }
            return
    }

    let activityView = addActivityIndicator(toView: self)
    var mutableRequest = URLRequest(url: url)
    mutableRequest.cachePolicy = NSURLRequest.CachePolicy.returnCacheDataElseLoad
    let request =
        Alamofire
            .request(mutableRequest)
            .response { (response) in
                DispatchQueue.main.async(execute: {
                    activityView.removeFromSuperview()
                })

                var success = false

                if response.response?.statusCode == 200 {

                    let strUniqueIdentifier_Closure = self.accessibilityLabel
                    if strUniqueIdentifier == strUniqueIdentifier_Closure {
                        success = true
                    }
                    else {
                        success = false
                        debugPrint("Unable to set image: uniqueIdentifier check failed")
                    }

                    if success, let data = response.data {
                        DispatchQueue.main.async(execute: {
                            self.image = UIImage(data: data)
                        })
                    }

                }

                if let completion = completion {
                    completion(success)
                }
    }
    self.accessibilityElements = [request]
}

private func addActivityIndicator(toView view: UIView) -> UIView {
    let sizeOfActivityContainer: CGFloat = 36.0

    let vwContainer = UIView(frame: CGRect(x: 0,
                                           y: 0,
                                           width: sizeOfActivityContainer,
                                           height: sizeOfActivityContainer))
    vwContainer.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.3)
    vwContainer.tag = 100

    vwContainer.layer.cornerRadius = sizeOfActivityContainer/2
    vwContainer.layer.masksToBounds = true

    vwContainer.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(vwContainer)

    vwContainer.addConstraint(NSLayoutConstraint(item: vwContainer,
                                                 attribute: .height,
                                                 relatedBy: .equal,
                                                 toItem: nil,
                                                 attribute: .notAnAttribute,
                                                 multiplier: 1,
                                                 constant: sizeOfActivityContainer))
    vwContainer.addConstraint(NSLayoutConstraint(item: vwContainer,
                                                 attribute: .width,
                                                 relatedBy: .equal,
                                                 toItem: nil,
                                                 attribute: .notAnAttribute,
                                                 multiplier: 1,
                                                 constant: sizeOfActivityContainer))
    view.addConstraint(NSLayoutConstraint(item: vwContainer,
                                          attribute: .centerX,
                                          relatedBy: .equal,
                                          toItem: view,
                                          attribute: .centerX,
                                          multiplier: 1,
                                          constant: 0))
    view.addConstraint(NSLayoutConstraint(item: vwContainer,
                                          attribute: .centerY,
                                          relatedBy: .equal,
                                          toItem: view,
                                          attribute: .centerY,
                                          multiplier: 1,
                                          constant: 0))

    let activityIndicator = UIActivityIndicatorView.init(activityIndicatorStyle: .white)
    activityIndicator.startAnimating()

    activityIndicator.translatesAutoresizingMaskIntoConstraints = false
    vwContainer.addSubview(activityIndicator)

    vwContainer.addConstraint(NSLayoutConstraint(item: activityIndicator,
                                                 attribute: .centerX,
                                                 relatedBy: .equal,
                                                 toItem: vwContainer,
                                                 attribute: .centerX,
                                                 multiplier: 1,
                                                 constant: 0))
    vwContainer.addConstraint(NSLayoutConstraint(item: activityIndicator,
                                                 attribute: .centerY,
                                                 relatedBy: .equal,
                                                 toItem: vwContainer,
                                                 attribute: .centerY,
                                                 multiplier: 1,
                                                 constant: 0))
    return vwContainer
}

答案 1 :(得分:0)

问题在于链接本身https://www.lancecamper.com/images/trailers/TT_1685_Int_hero.jpg。而是返回一个重定向到https://www.lancecamper.com的图像。