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

标签 ios swift firebase mapkit nsurlsession

我在下载图片时遇到了困难。我正在使用来自 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

最佳答案

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

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

相关文章:

swift - CTFontGetAdvancesForGlyphs 如何工作?

ios - 如何摆脱 UIWebView 上的状态栏背景?

swift - addDocument 完成处理程序永远不会被调用

ios - 不能直接加上#define变量

ios - 在用户登录时解析获取 facebook 个人资料图片

swift - 使用 Firebase 安全规则,如何在不公开整个节点的情况下检查可用的用户名?

Firebase 登录 promise 在我点击屏幕上的任意位置后才能解决

ios - 如何从 iOS 键盘内部检测 UITextInput 设置

ios - Swift:UITableView 不使用 reloadData 进行更新

android - 使用 firebase-core 或 play-services-analytics 在 Android 应用程序中添加 Google Analytics?