网址图片不适用于Swift Playgrounds中的UIButton

时间:2019-03-17 05:28:09

标签: ios swift swift-playground

我正在尝试使用以下代码从URL中创建UIImage,然后将URL输入浏览器即可正常工作。如果我更改背景颜色,该按钮也可以正常工作并显示,但是图像不会显示在按钮上。我正在使用最新版本的Swift Playgrounds。

let ARIconURLString = "https://lh3.googleusercontent.com/emT3b9yhU2o-uz-ZOoomqucgSvylLeWOKYKWbz88tP9zWJSzmIKiADxTWtxD39OiCO_aitwvhIzQ8ICmFbjSuZPTAgvgIEADjN3eft3IQewMVNNLsiKlYPQqnIzAvtn98Do5tBkAcNcY0Li1mX01UQmYyGBx8jF9oCytWirOxOwU68cF00oioqb1x-PVddQiMwcKf1UYtsqSUVXGvwK4G2KkSWOgvXYiH243bzt9PdVvDmz6rVsKqqTUTJewsKyyQf77xF772T8E_tkGQx0g-h8xgKhBhWJI21Zr2v1Z6A_c5xY7arR2ltA-m_yV30afoPm1wCz4dosnqNs7VqCdt2VnhMLhjc-NdFeVYG6b1LAmMDyZOFkTw_xrmnh-Z416ffolEtcZMjuNzEbHwBFwFDsmpMJj-R4SKXrRxtgBrYwRCpG1G3icgI_0G-Kj_rHIHrw4nMfHb708X5_K1SKIyeL5LIThfnxk5JOuS11vX680nFMRu9kmzrP3IdFoJT-6JLYPHtuTgS0kXfcoN7F3QSKd6E2Fl-X8uOxNRSbl9lvKk0I7ymChF5XFHJh5Q1zWCFxczDf8gEdQ1gKGJn4IrzISSwGqw51U2BgGQ6t5qV26CYIoRVeG1tZYUPBdtOdwrOPXgoP6oZDlemcfuJhxJxC4qAV8CSA=s512-no"
    let ARIconURL = URL(string: ARIconURLString)!
    let ARIconData = try! Data(contentsOf: ARIconURL)
    let ARIcon = UIImage(data: ARIconData)
    ARButton.contentMode = .scaleAspectFit
    ARButton.setImage(ARIcon, for: .normal)

1 个答案:

答案 0 :(得分:0)

使用同步代码通常是一个坏习惯。 通常您可以使图像异步:

   final private func downloadFrom(urlString: String?){


    self.imageView.image = nil

    guard let urlString = urlString, let myURL = URL(string: urlString) else{
        return
    }

    let session = URLSession.shared

    self.task = session.dataTask(with: myURL) { (data: Data?, response: URLResponse?, error: Error?) in

        if let error = error  {
            print(error)
            return
        }


    guard let data = data else{
        return
    }


    if 200 ... 299 ~= statusCode {            
        self.loadImage(data: data)
    }else{
        // self.manageError(data: data)
    }

}

self.task?.resume()
}




final private func loadImage(data : Data){
        let image = UIImage(data: data)
        DispatchQueue.main.async {
            self.imageView.image = image
        }
}