菜鸟教程小白 发表于 2022-12-11 18:42:23

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


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

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

<p>这是我的 viewDidLoad:</p>

<pre><code>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(&#34;users&#34;).child((FIRAuth.auth()?.currentUser?.uid)!).child(&#34;dogs&#34;)

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

            let snapshotValue = snapshot.value as! Dictionary&lt;String, String&gt;
            let dogID = snapshotValue[&#34;dogID&#34;]!

            let dogRef = FIRDatabase.database().reference().child(&#34;dogs&#34;).child(dogID)
            dogRef.observeSingleEvent(of: .value, with: { (snap) in
                print(&#34;Found dog data!&#34;)
                let value = snap.value as! Dictionary&lt;String, String&gt;

                let name = value[&#34;name&#34;]!
                let breed = value[&#34;breed&#34;]!
                let creator = value[&#34;creator&#34;]!
                let score = Int(value[&#34;score&#34;]!)!
                let lat = Double(value[&#34;latitude&#34;]!)!
                let lon = Double(value[&#34;longitude&#34;]!)!
                let url = value[&#34;imageURL&#34;]!
                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()
            })
      }
    })
}
</code></pre>

<p>这是我的 mapView 和注释方法:</p>

<pre><code>func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -&gt; MKAnnotationView? {
    if(annotation is MKUserLocation){
      return nil
    }

    let ident = &#34;pin&#34;

    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 = [&#34;dogPhotoView&#34;: dogPhotoView]
    dogPhotoView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: &#34;H:&#34;, options: [], metrics: nil, views: views))
    dogPhotoView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: &#34;V:&#34;, 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
}
</code></pre>

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

<pre><code>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(&#34;init(coder:) has not been implemented&#34;)
    }
}
</code></pre>

<p>这是我的调试器的照片:
<a href="/image/2umm0.png" rel="noreferrer noopener nofollow"><img src="/image/2umm0.png" alt="enter image description here"/></a> </p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>将 <code>self.map.addAnnotation(annotation)</code> 移动到 URLSession.shared.dataTask 完成处理程序。目前图片在 map 添加注释后设置为Dog对象。不要忘记用 <code>OperationQueue.main.addOperation</code> 包装 addAnnotation(_:) 调用。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - URLSession 数据任务后 UIImage 未加载,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/46257296/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/46257296/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - URLSession 数据任务后 UIImage 未加载