2017-09-16 7 views
0

イメージのダウンロードに苦労しています。 Firebaseの画像URLを使用してjpegをダウンロードし、マップビューのコールアウトで画像を使用しています。現在、コールアウトは正しいサイズで表示されますが、画像や字幕は表示されません。イメージアセットを手動で渡すと完全に動作します。イメージURLは、newDogオブジェクトに完全に保存されます。イメージをデバッグして検査すると、イメージはメモリに表示されますが、空に見えます。UIImageがURLSessionデータタスクの後に読み込まれません。

これは、画像のダウンロードが完了する前にコールアウトビューを読み込むことと多分関係があると思いますか?

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() 
      }) 
     } 
    }) 
} 

ここだ私のMapViewと注釈方法::私は、カスタム注釈クラスを使用してい

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 
} 

は、ここに私のviewDidLoadです。ここではそれだ: enter image description here

答えて

0

吹き出しイメージビューの作成中に問題が発生しました。私はimageViewを作成しましたが、それをスーパービューのサブビューとして追加したことはありませんでした。どのような愚かな監督!

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 

     DispatchQueue.main.async { 
      dogPhotoView.addSubview(imageView) 
      self.view.layoutIfNeeded() 
     } 

    } 

    annotationView.detailCalloutAccessoryView = dogPhotoView 
} 
0

非同期で動作しますdataTask

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") 
    } 
} 

ここに私のデバッガの写真です。補完ハンドラにアノテーションを作成するコードに移動する必要があります。

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() 
+0

私はこれを試しましたが、私はまだ同じ結果を得ています。私の編集したコードを見てください。 @vadian –

+1

提案を適用するコードは編集しないでください。それは助けようとしている人たちを混乱させます – vadian

+0

私はそれを前に考えなかったことを感謝します。 –

0

self.map.addAnnotation(annotation)をURLSession.shared.dataTask補完ハンドラに移動します。マップがアノテーションを追加した後、現在、画像はDogオブジェクトに設定されています。 OperationQueue.main.addOperationでaddAnnotation(_ :)呼び出しをラップするのを忘れないでください。

関連する問題