The question might not sound correctly worded but I don't know how to else put it, Apologies.
I am using Google Maps API in my project, to fetch the results and put them in a CollectionView using the MSPeekCollectionViewDelegateImplementation POD
Please any help is so much appreciated!
Always on the first run, as seen in the picture below, it never shows up.
On the second run however it works perfectly, as seen below:
API manager class:
import Foundation
import CoreData
class GoogleMapsAPIManager {
var bloodBanksArray = [BloodBanksModel]()
func fetchCity(latitude: CLLocationDegrees, longitude: CLLocationDegrees, raduis: Double){
let urlString = "\(K.googleMapsAPI)&location=\(latitude),\(longitude)&radius=\(raduis)&key=\(K.apiKey)"
print(urlString)
performRequest(with: urlString)
}
//MARK: - Decoding JSON
func performRequest(with urlString: String){
if let url = URL(string: urlString) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
return
}
if let safeData = data {
self.parseJSON(bloodBankData: safeData)
}
}
task.resume()
}
}
func parseJSON(bloodBankData: Data) {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(BloodBanksData.self, from: bloodBankData)
for i in 0...decodedData.results.count - 1 {
bloodBanksArray.append(BloodBanksModel(name: decodedData.results[i].name, photo: decodedData.results[i].photos?[0].photoReference ?? "ATtYBwJjqXlw3DMdL74SRtgG_GRA3LkAET6hDJXHWtkQMaOTo1B3Gx9jrDTXFLFabGStSxX8BiYdLAnknF7A9ynw33KKyUh5Oc55A9vXzo_6nd4mnk5Sx-iOqMNaw21dk0C424PWaio9GiogQaKecYxOT1q-bmj30syypZmyxkjF7r3-gFyC", open_now: decodedData.results[i].openingHours?.openNow ?? false, longitude: decodedData.results[i].geometry.location.lng, latitude: decodedData.results[i].geometry.location.lat, vincinity: decodedData.results[i].vicinity, rating: decodedData.results[i].rating, placeId: decodedData.results[i].placeId, lat: decodedData.results[i].geometry.location.lat, lng: decodedData.results[i].geometry.location.lng))
}
print("bossins \(bloodBanksArray)")
} catch {
print(error)
}
}
}
Blood banks Model:
import Foundation
struct BloodBanksModel {
let name: String
let photo: String
let open_now: Bool
let longitude: Double
let latitude: Double
let vincinity: String
let rating: Double
let placeId: String
let lat: Double
let lng: Double
}
Blood Bank Data:
import Foundation
// MARK: - BloodBanksData
struct BloodBanksData: Codable {
let results: [Result]
enum CodingKeys: String, CodingKey {
case results
}
}
// MARK: - Result
struct Result: Codable {
let geometry: Geometry
let name: String
let openingHours: OpeningHours?
let photos: [Photo]?
let rating: Double
let vicinity: String
let placeId: String
enum CodingKeys: String, CodingKey {
case geometry, name
case openingHours = "opening_hours"
case photos
case rating
case vicinity
case placeId = "place_id"
}
}
// MARK: - Geometry
struct Geometry: Codable {
let location: Location
}
// MARK: - Location
struct Location: Codable {
let lat, lng: Double
}
// MARK: - OpeningHours
struct OpeningHours: Codable {
let openNow: Bool
enum CodingKeys: String, CodingKey {
case openNow = "open_now"
}
}
// MARK: - Photo
struct Photo: Codable {
let photoReference: String
enum CodingKeys: String, CodingKey {
case photoReference = "photo_reference"
}
}
The VC:
let locationManager = CLLocationManager()
var googleMapsAPIManager = GoogleMapsAPIManager()
override func viewDidLoad() {
super.viewDidLoad()
//locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
var currentLocation: CLLocation!
if
CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == .authorizedAlways
{
currentLocation = locationManager.location
googleMapsAPIManager.fetchCity(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude, raduis: 2000.0)
}
configureCollectionView()
}
func configureCollectionView() {
collectionView.dataSource = self
collectionView.delegate = self
let cellNib = UINib(nibName: K.BloodBanks.bloodBanksCellNibName, bundle: nil)
collectionView.register(cellNib,
forCellWithReuseIdentifier: K.BloodBanks.bloodBankCellIdentifier)
behavior = MSCollectionViewPeekingBehavior(cellSpacing: 20)
behavior = MSCollectionViewPeekingBehavior(cellPeekWidth: 40)
behavior = MSCollectionViewPeekingBehavior(minimumItemsToScroll: 1)
behavior = MSCollectionViewPeekingBehavior(maximumItemsToScroll: 3)
behavior = MSCollectionViewPeekingBehavior(numberOfItemsToShow: 1)
collectionView.configureForPeekingBehavior(behavior: behavior)
}
}
// MARK: - UICollectionViewDataSource Methods
extension LandingViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return googleMapsAPIManager.bloodBanksArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: K.BloodBanks.bloodBankCellIdentifier, for: indexPath) as! BloodBanksCell
DispatchQueue.main.async {
cell.bloodBankName.text = self.googleMapsAPIManager.bloodBanksArray[indexPath.row].name
cell.bloodBankImageView.sd_setImage(with: URL(string: "\(K.googleMapsImageAPI)&photoreference=\(self.googleMapsAPIManager.bloodBanksArray[indexPath.row].photo)&key=\(K.apiKey)"), placeholderImage: #imageLiteral(resourceName: "bloodbank4"))
}
return cell
}
}
// MARK: - UICollectionViewDelegate Methods
extension LandingViewController: UICollectionViewDelegate {
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
behavior.scrollViewWillEndDragging(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset)
}
}

