• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - URLSession 数据任务后 UIImage 未加载

[复制链接]
菜鸟教程小白 发表于 2022-12-11 18:42:23 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我很难下载图片。我正在使用 Firebase 中的图像 URL 下载 jpeg,并在 map View 标注中使用该图像。目前,标注以正确的大小显示,但没有图像或字幕。当我手动传入图像 Assets 时,它可以完美运行。图像 URL 完美地保存到 newDog 对象。当我调试和检查图像时,它出现在内存中但看起来是空的。

我认为这可能与在图像下载完成之前加载标注 View 有关?

这是我的 viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()

    self.map.mapType = .standard
    self.map.showsUserLocation = true
    self.map.userTrackingMode = .follow
    self.map.delegate = self
    self.map.mapType = .hybrid
    let userDogRef = FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("dogs")

    userDogRef.observe(.childAdded, with: { (snapshot) in
        if snapshot.value == nil {
            print("no new dog found")
        } else {
            print("new dog found")

            let snapshotValue = snapshot.value as! Dictionary<String, String>
            let dogID = snapshotValue["dogID"]!

            let dogRef = FIRDatabase.database().reference().child("dogs").child(dogID)
            dogRef.observeSingleEvent(of: .value, with: { (snap) in
                print("Found dog data!")
                let value = snap.value as! Dictionary<String, String>

                let name = value["name"]!
                let breed = value["breed"]!
                let creator = value["creator"]!
                let score = Int(value["score"]!)!
                let lat = Double(value["latitude"]!)!
                let lon = Double(value["longitude"]!)!
                let url = value["imageURL"]!
                let location = CLLocationCoordinate2D(latitude: lat, longitude: lon)

                let newDog = Dog()
                newDog.name = name
                newDog.breed = breed
                newDog.creator = creator
                newDog.score = score
                newDog.imageURL = url
                newDog.location = location

                let downloadURL = URL(string: newDog.imageURL)!
                URLSession.shared.dataTask(with: downloadURL, completionHandler: { (data, response, error) in
                    if error != nil {
                        print(error!)
                        return
                    }
                    newDog.picture = UIImage(data: data!)!
                    self.dogs.append(newDog)
                    let annotation  = CustomAnnotation(location: newDog.location, title: newDog.name, subtitle: newDog.creator)
                    DispatchQueue.main.async {
                        self.map.addAnnotation(annotation)
                    }

                }).resume()
            })
        }
    })
}

这是我的 map View 和注释方法:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if(annotation is MKUserLocation){
        return nil
    }

    let ident = "pin"

    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: ident)
    if annotationView == nil {
        annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: ident)
        annotationView?.canShowCallout = true
    } else {
        annotationView!.annotation = annotation
    }
    configureDetailView(annotationView!)
    return annotationView
}

func configureDetailView(_ annotationView: MKAnnotationView) {
    let width = 300
    let height = 300

    let dogPhotoView = UIView()
    let views = ["dogPhotoView": dogPhotoView]
    dogPhotoView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[dogPhotoView(\(height))]", options: [], metrics: nil, views: views))
    dogPhotoView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[dogPhotoView(\(width))]", options: [], metrics: nil, views: views))


    for dog in self.dogs {
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: width, height: height))
        imageView.image = dog.picture
    }

    annotationView.detailCalloutAccessoryView = dogPhotoView
}

我正在使用自定义注释类。就是这样:

class CustomAnnotation: NSObject, MKAnnotation {
    var coordinate : CLLocationCoordinate2D
    var title: String?
    var subtitle: String?

    init(location: CLLocationCoordinate2D, title: String, subtitle: String) {
        self.coordinate = location
        self.title = title
        self.subtitle = title
        super.init()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder has not been implemented")
    }
}

这是我的调试器的照片: enter image description here



Best Answer-推荐答案


self.map.addAnnotation(annotation) 移动到 URLSession.shared.dataTask 完成处理程序。目前图片在 map 添加注释后设置为Dog对象。不要忘记用 OperationQueue.main.addOperation 包装 addAnnotation(_ 调用。

关于ios - URLSession 数据任务后 UIImage 未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46257296/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap