我很难进行图片下载。我使用Firebase中的图片网址下载jpeg,并在地图视图标注中使用该图片。目前,标注以正确的大小显示,但没有图像或副标题。当我手动传入图像资源时,它完美地工作。图像URL完美保存到newDog对象。当我调试并检查图像时,它出现在内存中但看起来是空的。
我想也许这与在图像下载完成之前加载标注视图有关?
这是我的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()
})
}
})
}
这是我的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
}
我正在使用自定义注释类。这是:
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")
}
}
答案 0 :(得分:0)
dataTask
异步工作。您应该移动到代码以在完成处理程序中创建注释。
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()
答案 1 :(得分:0)
将self.map.addAnnotation(annotation)
移至URLSession.shared.dataTask完成处理程序。当地图添加注释后,当前图片设置为Dog对象。不要忘记用OperationQueue.main.addOperation
包装addAnnotation(_ :)调用。
答案 2 :(得分: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
}