i've add Pull To Refresh on UITableView on my Swift project successful, on another ViewController i'm not able to show it.
On the others view the code is the same without LocationManager functions.
I don't know where is my error!
Below my code:
import UIKit
import CoreLocation
class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CLLocationManagerDelegate {
var locationManager: CLLocationManager!
var locationCoordinates: CLLocationCoordinate2D!
#IBOutlet weak var bannerView: GADBannerView!
var dati = NSMutableArray()
var datiComplete = NSDictionary()
#IBOutlet weak var tableView: UITableView!
var arrayOfData: [MyData] = [MyData]()
var url:NSURL!
var refreshControl = UIRefreshControl()
var dateFormatter = NSDateFormatter()
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager = CLLocationManager()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest //Battery drain!
self.locationManager.distanceFilter = 1
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
searchUser()
self.dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
self.dateFormatter.timeStyle = NSDateFormatterStyle.LongStyle
self.refreshControl = UIRefreshControl()
self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.insertSubview(refreshControl, atIndex: 0)
self.handleRefresh()
}
func refresh(sender:AnyObject)
{
println("Refresh work!")
self.handleRefresh()
}
func handleRefresh() {
if locationManager.location != nil {
url = NSURL(string: "http://www.myURL.com/data.php?lat=\(locationManager.location.coordinate.latitude)&lon=\(locationManager.location.coordinate.longitude)&max=15&when=now")!
} else {
url = NSURL(string: "http://www.myURL.com/data.php?lat=41&lon=11&max=10&when=now")!
}
//println("Call URL!!")
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
//var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
response, data, error in
if (error != nil) {
return
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
var error: NSError?
self.dati = (NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &error) as! NSDictionary)["spots"] as! NSMutableArray
if (error != nil){
return
}
// **** Json Parsing *****
dispatch_async(dispatch_get_main_queue()){
self.tableView.reloadData()
self.tableView.delegate = self
self.tableView.dataSource = self
}
}
})
let now = NSDate()
let updateString = "Last Updated at " + self.dateFormatter.stringFromDate(now)
self.refreshControl.attributedTitle = NSAttributedString(string: updateString)
if self.refreshControl.refreshing
{
self.refreshControl.endRefreshing()
}
self.tableView?.reloadData()
refreshControl.endRefreshing()
}
func searchUser(){
println("Start Search User")
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestAlwaysAuthorization()
self.locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!){
println("Start Location Manager Func")
self.locationCoordinates = manager.location.coordinate
self.locationManager.stopUpdatingLocation()
println("**************** locations = \(self.locationCoordinates.latitude) \(self.locationCoordinates.longitude)")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.setNavigationBarItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayOfData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: ViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! ViewCell
cell.backgroundColor = UIColor.whiteColor()
let usr = arrayOfData[indexPath.row]
cell.setCell(<Cell-data>)
return cell
}
var selectedSpot:String? = nil
var selectedSpotIndex:Int? = nil
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "GoSpotDetails" {
var tabBarC : TabBarController = segue.destinationViewController as! TabBarController
var caseIndex = tableView!.indexPathForSelectedRow()!.row
var selectedCase = self.arrayOfSpotsTemp[caseIndex]
tabBarC.DataDetail = selectedCase
}
}
}
Thanks a lot.
Well, your code needs lot of changes. Let me give you some suggestions.
Instead of self.tableView.insertSubview(refreshControl, atIndex: 0) try to use tableView.addSubview(refreshControl). Look thedifference between add and insert subview here
Define another function to populate view. Eg. func populateView()
Replace self.handleRefresh() with self.populateView()
Replace
self.refreshControl.addTarget(
self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged
)
with
self.refreshControl.addTarget(
self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged
)
In func handleRefresh() initiate the refreshing by using refreshControl.beginRefreshing() then remove all the objects, reload the tableView, end refreshing and populate the view.
EDIT
I have misunderstood your question.
Why its not working in other view?
Its because in UITableViewController refreshControl comes pre-fit, a regular ViewController does not.
So what to do?
Here is a snippet defining a lazily instantiated variable which creates and configures a UIRefreshControl:
lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(
self, action: "handleRefresh", forControlEvents: .ValueChanged
)
return refreshControl
}()
In viewDidLoad() add UIRefreshControl as a subview to the tableView as:
self.tableView.addSubview(self.refreshControl)
Hope this helps you to understand!
Related
I am an intermediate Swift developer and I am creating an app that involves using a search function to find an address and pinpoint said address on a map. I followed a tutorial on how to achieve this and everything is functional besides the search function itself. Whenever I type in the UIsearchbar my search results tableview controller is instantiated, however, the table view is blank and does not update as I type. An address API call should be present.
Below is my code for the search table
import UIKit
import MapKit
class LocationSearchTable : UITableViewController {
var resultSearchController:UISearchController? = nil
var handleMapSearchDelegate:HandleMapSearch? = nil
var matchingItems:[MKMapItem] = []
var mapView: MKMapView? = nil
#IBOutlet var searchTableView: UITableView!
}
extension LocationSearchTable : UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
searchController.showsSearchResultsController = true
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
guard let mapView = mapView,
let searchBarText = searchController.searchBar.text else { return }
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = searchBarText
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start { response, _ in
guard let response = response
else {
return
}
self.matchingItems = response.mapItems
self.tableView.reloadData()
}
}
}
extension LocationSearchTable {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return matchingItems.count
}
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
let selectedItem = matchingItems[indexPath.row].placemark
cell.textLabel?.text = selectedItem.name
cell.detailTextLabel?.text = ""
return cell
}
}
extension LocationSearchTable {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedItem = matchingItems[indexPath.row].placemark
handleMapSearchDelegate?.dropPinZoomIn(placemark: selectedItem)
dismiss(animated: true, completion: nil)
}
}
This is my code for my initial view controller
import UIKit
import MapKit
import CoreLocation
protocol HandleMapSearch {
func dropPinZoomIn(placemark:MKPlacemark)
}
//for some reason my location delegate is not working (resolved)
class locationViewController: UIViewController, UISearchResultsUpdating, UISearchBarDelegate {
func updateSearchResults(for searchController: UISearchController) {
return
}
var selectedPin:MKPlacemark? = nil
var resultSearchController:UISearchController? = nil
#IBOutlet weak var eventLocationMapView: MKMapView!
#IBOutlet weak var backButton: UIButton!
let locationManager = CLLocationManager()
let regionInMeters: Double = 10000
override func viewDidLoad() {
super.viewDidLoad()
resultSearchController?.searchResultsUpdater = self
let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "LocationSearchTable") as! LocationSearchTable
resultSearchController = UISearchController(searchResultsController: locationSearchTable)
resultSearchController?.searchResultsUpdater = locationSearchTable
resultSearchController?.searchBar.delegate = self
locationSearchTable.mapView = eventLocationMapView
let searchBar = resultSearchController!.searchBar
searchBar.sizeToFit()
searchBar.placeholder = "Search for places"
//this is the search bar
navigationItem.titleView = resultSearchController?.searchBar
resultSearchController?.hidesNavigationBarDuringPresentation = false
resultSearchController?.obscuresBackgroundDuringPresentation = true
definesPresentationContext = true
locationSearchTable.handleMapSearchDelegate = self
//all of this is in regards to the search functionality
locationManager.startUpdatingLocation()
self.checkLocationAuthorization()
self.checkLocationServices()
self.navigationController?.isNavigationBarHidden = false
// Do any additional setup after loading the view.
locationManager.requestWhenInUseAuthorization()
//this pushes the user request. The issue was most likely in the switch statement
locationManager.delegate = self
locationManager.requestLocation()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
//solved it but we will probably have to go back to this
self.centerViewOnUserLocation()
}
#IBAction func backButtonTapped(_ sender: Any) {
self.transitionBackToCreateEventVC()
}
func transitionBackToCreateEventVC (){
let createEventViewController = self.storyboard?.instantiateViewController(identifier: "createEventVC")
self.view.window?.rootViewController = createEventViewController
self.view.window?.makeKeyAndVisible()
}
func centerViewOnUserLocation() {
if let location = locationManager.location?.coordinate {
let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
eventLocationMapView.setRegion(region, animated: true)
//this function centers the map onto the location of the user
}
}
func setUpLocationManager(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
func checkLocationServices(){
if CLLocationManager.locationServicesEnabled(){
setUpLocationManager()
checkLocationAuthorization()
} else {
//show alert letting the user know they have to turn this on
}
}
func checkLocationAuthorization() {
let locationManager = CLLocationManager()
switch locationManager.authorizationStatus {
case .authorizedWhenInUse:
eventLocationMapView.showsUserLocation = true
// We want the users location while the app is in use
break
case .denied:
//show alert instructing how to turn on permissions
break
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
return
case .restricted:
//show an alert
break
case .authorizedAlways:
// we don't want this
break
#unknown default:
return
//I dont know if we need this code
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension locationViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
locationManager.requestLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
let region = MKCoordinateRegion(center: location.coordinate, latitudinalMeters: 0.05 , longitudinalMeters: 0.05)
eventLocationMapView.setRegion(region, animated: true)
}
}
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("error:: \(error)")
}
}
extension locationViewController: HandleMapSearch {
func dropPinZoomIn(placemark:MKPlacemark){
// cache the pin
selectedPin = placemark
// clear existing pins
eventLocationMapView.removeAnnotations(eventLocationMapView.annotations)
let annotation = MKPointAnnotation()
annotation.coordinate = placemark.coordinate
annotation.title = placemark.name
if let city = placemark.locality,
let state = placemark.administrativeArea {
annotation.subtitle = "\(city) \(state)"
}
eventLocationMapView.addAnnotation(annotation)
let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
let region = MKCoordinateRegion(center: placemark.coordinate, span: span)
eventLocationMapView.setRegion(region, animated: true)
}
}
I think the you should make a property to hold the MKLocalSearch object in your LocationSearchTable class.
class LocationSearchTable : UITableViewController {
private var search: MKLocalSearch?
// ...
}
extension LocationSearchTable : UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController) {
guard let mapView = mapView,
let searchBarText = searchController.searchBar.text else { return }
// if there is an ongoing search, cancel it first.
self.search?.cancel()
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = searchBarText
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start { response, error in
guard let response = response
else {
return
}
self.matchingItems = response.mapItems
self.tableView.reloadData()
}
// make sure `search` is not released.
self.search = search
}
}
The problem of the original code is that, the search object, instance of MKLocalSearch class will be released when finishes executing updateSearchResultsForSearchController method, since there is no strong reference to it, and start's callback will never be called, so your table view will never be reloaded.
What we do is just make a strong ref to it, and make sure it is not released before completion handler is called.
I'm encoding images selected by the user, then saving to USerDefault. So, I retrieve these images by decoding and converting to an Array of UIImages, where I populate my UITableView. My goal is being able to terminate the App and when I open again, the UITableView still populated, I want to persist the user data.
Everything worked perfectly, I got what I wanted but after a couple tries I got the following error:
Terminating app due to uncaught exception 'NSRangeException', reason:
' -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty
NSArray'
What would be the best way for me to do what I want?
Here is where the data should be retrieved:
class ViewController: UIViewController, CLLocationManagerDelegate, UITableViewDataSource, dataReceivedDelegate {
func dataReceived(nameSaved: NSArray) {
nameSaved1 = nameSaved
// imagemCell = fotoSaved
self.itensTableView.reloadData()
}
#IBOutlet weak var itensTableView: UITableView!
//Notification
let content = UNMutableNotificationContent()
//
var locationManager:CLLocationManager = CLLocationManager()
var currentLocation: CLLocation?
let region = CLBeaconRegion(proximityUUID: UUID(uuidString: "DD07D751-FBE1-430C-973A-281F9DA59A39")!, identifier: "Estimotes")
var arrayNomes = NSMutableArray()
var nomeReceived = ""
var qtd:Int = 0
var imagemCell = [NSData]()
var nameSaved1 = NSArray()
var dataSaved = [NSData]()
var imageSaved = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
if isKeyPresentInUserDefaults(key: "namesSavedArray") == true{
nameSaved1 = UserDefaults.standard.array(forKey: "namesSavedArray") as! [String] as NSArray
itensTableView.reloadData()
}
if isKeyPresentInUserDefaults(key: "fotoSaved") == true{
// Load the image
imagemCell = UserDefaults.standard.object(forKey: "fotoSaved") as! [NSData]
for uiimage in imagemCell {
let imageConverted = UIImage(data: uiimage as Data)
imageSaved.append(imageConverted!)
itensTableView.reloadData()
}
}
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
//LocationManager
locationManager.delegate = self
if (CLLocationManager.authorizationStatus() != CLAuthorizationStatus.authorizedWhenInUse) {
locationManager.requestWhenInUseAuthorization()
}
locationManager.startRangingBeacons(in: region)
}
func isKeyPresentInUserDefaults(key: String) -> Bool {
return UserDefaults.standard.object(forKey: key) != nil
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "addVc" {
let vc:adicionarNovoItemVc = segue.destination as! adicionarNovoItemVc
vc.delegate = self
}
}
func rangeBeacons(){
let uuid = UUID(uuidString: "DD07D751-FBE1-430C-973A-281F9DA59A39")
let major:Int = 1
let minor:Int = 1
let identifier = "Bruz IBeacon"
let region = CLBeaconRegion(proximityUUID: uuid!, major: CLBeaconMajorValue(major), minor: CLBeaconMinorValue(minor), identifier: identifier)
locationManager.startRangingBeacons(in: region)
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .restricted:
print("Location access was restricted.")
case .denied:
print("User denied access to location.")
case .notDetermined:
print("Location status not determined.")
case .authorizedAlways: fallthrough
case .authorizedWhenInUse:
print("Location status is OK.")
}
if status == .authorizedAlways{
rangeBeacons()
}
}
// Handle incoming location events.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location: CLLocation = locations.last!
print("Location: \(location)")
}
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
guard let discoveredBeacon = beacons.first?.proximity else {
print("Beacon nao encontrado"); return}
switch discoveredBeacon {
case .immediate:
beaconMuitoProximo()
self.view.backgroundColor = .green
case .near: break
// beaconProximo()
// self.view.backgroundColor = .orange
case .far:
beaconLonge()
self.view.backgroundColor = .red
case .unknown:
self.view.backgroundColor = .black
}
}
// Handle location manager errors.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
locationManager.stopUpdatingLocation()
print("Error: \(error)")
}
func beaconMuitoProximo(){
//Notificacoes de perda de objetos
// self.content.title = "Seguro"
// self.content.body = "Suas coisas estao perto de voce =)"
// self.content.sound = UNNotificationSound.default
// let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
// let request = UNNotificationRequest(identifier: "testIdentifierPerto", content: self.content, trigger: trigger)
// UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
//
}
func beaconProximo(){
}
func beaconLonge(){
// create a sound ID, in this case its the tweet sound.
let systemSoundID: SystemSoundID = 1016
// to play sound
AudioServicesPlaySystemSound (systemSoundID)
}
#IBAction func botaoAdicionar(_ sender: UIButton) {}
//TableView
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let item = objetos[indexPath.row]
let cell = itensTableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! tableviewCell
cell.nameCell.text = nameSaved1[indexPath.row] as? String//Nil value
cell.imageViewCell.image = imageSaved[indexPath.row] //Nil value
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return imageSaved.count
}
}
Here is where I'm saving the data:
protocol dataReceivedDelegate {
func dataReceived(nameSaved:NSArray)
}
class adicionarNovoItemVc: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
#IBOutlet weak var textFieldNome: UITextField!
#IBOutlet weak var namePreview: UILabel!
#IBOutlet weak var imagePreview: UIImageView!
let imagePicker = UIImagePickerController()
let picker = UIImagePickerController()
var arrayName = [String]()
var arrayFotoData = [NSData]()
var delegate:dataReceivedDelegate? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.textFieldNome.delegate = self
if isKeyPresentInUserDefaults(key: "namesSavedArray") == true{
arrayName = UserDefaults.standard.array(forKey: "namesSavedArray") as! [String]
}
if isKeyPresentInUserDefaults(key: "fotoSaved") == true{
arrayFotoData = UserDefaults.standard.array(forKey: "fotoSaved") as! [NSData]
}
}
func isKeyPresentInUserDefaults(key: String) -> Bool {
return UserDefaults.standard.object(forKey: key) != nil
}
#IBAction func botaoAdcFoto(_ sender: UIButton) {
picker.allowsEditing = true
picker.delegate = self
picker.sourceType = .photoLibrary
if let mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary) {
picker.mediaTypes = mediaTypes
}
present(picker, animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[.originalImage] as? UIImage {
self.imagePreview.image = image
self.namePreview.text = self.textFieldNome.text
//Encode Image
let dataSaved:NSData = image.pngData()! as NSData
arrayFotoData.append(dataSaved)
UserDefaults.standard.set(arrayFotoData, forKey: "fotoSaved")
}
self.picker.dismiss(animated: true, completion: nil)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.textFieldNome.resignFirstResponder()
return true
}
#IBAction func botaoAdcItem(_ sender: UIButton) {
if (self.namePreview!.text != nil) && (self.imagePreview!.image != nil) {
if delegate != nil {
arrayName.append(self.namePreview.text!)
delegate?.dataReceived(nameSaved: arrayName as NSArray)
UserDefaults.standard.set(arrayName, forKey: "namesSavedArray")
self.navigationController?.popViewController(animated: true)
}
}
else {return}
}
}
That's how the app should work:
This screen is where the UITableView is located, so the data should be persist here:
This screen is where the data should be set and saved:
After press the button, the screen should be dismissed and reload the UITableView containing the data.
I have the Objective-c version of the code which you may need, kindly try to create the swift version.
So, to save/write the image data to the application's folder you can do as
//to write the image in folder
NSData *pngData = UIImagePNGRepresentation(image);
[pngData writeToFile:[[AlertHelper sharedAlertManager] documentsPathForFileName:#"The name for your image"] atomically:YES]; //Write the file
I have used an helper method in the above code to ease the process and use it in at various class files.
And to Read the image data,
NSData *pngData1 = [NSData dataWithContentsOfFile:[[AlertHelper sharedAlertManager] documentsPathForFileName:#"The same name you used to write for your image"]];
UIImage *image = [UIImage imageWithData:pngData1];
And the Helper methood is
// to write and read files in paths
- (NSString *)documentsPathForFileName:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSLog(#"%#",[documentsPath stringByAppendingPathComponent:name]); // to check if the name used for image.
return [documentsPath stringByAppendingPathComponent:name];
}
UPDATE:-
For the Swift Version i came across something which may be useful.
I think the problem you are having related to the as! [String]
Just because the key exists doesn’t mean that you won’t get nil back.
Use as? [String] ?? []
So if nil is returned you will have an empty array.
Just call UserDefaults.standard.synchronize() after set new value to UserDefault, it should trigger a synchronization for actually storing new value.
I'm currently encountering a problem within my app. I have a view on which I can search and select a place with the GoogleMaps / GooglePlaces SDK. I'm also using Google Autocomplete for completing the search string.
The problem: When I visit the first view, everything is still fine, but after I have entered a search string and press search, my memory usage increases for about 10-20 MB. When I unwind the view and save it, the memory won't be released and is still in my total memory. Therefore if I save a couple of places I'll get an overflow and the App will crash.
Do you guys know where my problem is in the code? I'm already searching for hours...
I looked for Database request which sets up listeners but in fact nothing happens regarding this in these classes. Maybe it has something to do with Googlemaps, that it keeps up the connection?
I attached 2 screenshots from my app and the 2 classes for these are the following:
import UIKit
import GoogleMaps
class AddNewPlaceViewController: UIViewController, UISearchBarDelegate, LocateOnTheMap {
//Outlets
#IBOutlet weak var googleMapsContainer: UIView!
//Variables
var googleMapsView: GMSMapView!
var searchResultController: SearchResultsController!
var resultsArray = [String]()
//Result
var locationAsCoords = [String:Double]()
var locationAdress = String()
//Error
var alerts = Alerts()
var alertActions = AlertActions()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
self.googleMapsView = GMSMapView(frame: self.googleMapsContainer.frame)
self.view.addSubview(self.googleMapsView)
searchResultController = SearchResultsController(view: self)
searchResultController.delegate = self
showSearchBar()
}
#IBAction func saveButtonTapped(sender: AnyObject) {
if self.locationAdress.isEmpty {
// Error message if no address has been searched
NSLog("Event address ist empty.")
let alert = alerts.alertNoLocationAddress
let alertCancel = alertActions.alertActionCancel
if(alert.actions.count == 0){
alert.addAction(alertCancel)
}
self.presentViewController(alert, animated: true, completion: nil)
} else {
// exits with the saveAndUnwind segue
self.performSegueWithIdentifier("saveAndUnwind", sender: self)
}
}
/**
action for search location by address
- parameter sender: button search location
*/
#IBAction func searchWithAddress(sender: AnyObject) {
showSearchBar()
}
/**
Locate map with latitude and longitude after search location on UISearchBar
- parameter lon: longitude location
- parameter lat: latitude location
- parameter title: title of address location
*/
func locateWithLongitude(lon: Double, andLatitude lat: Double, andTitle title: String) {
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.googleMapsView.clear()
let position = CLLocationCoordinate2DMake(lat, lon)
let marker = GMSMarker(position: position)
let camera = GMSCameraPosition.cameraWithLatitude(lat, longitude: lon, zoom: 15)
self.googleMapsView.camera = camera
marker.title = "\(title)"
marker.map = self.googleMapsView
}
}
func showSearchBar(){
let searchController = UISearchController(searchResultsController: searchResultController)
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.delegate = self
self.presentViewController(searchController, animated: true, completion: nil)
}
/**
Searchbar when text change
- parameter searchBar: searchbar UI
- parameter searchText: searchtext description
We can use filters here in the autocompleteQuery
*/
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
let placeClient = GMSPlacesClient()
placeClient.autocompleteQuery(searchText, bounds: nil, filter: nil) { (results, error: NSError?) -> Void in
self.resultsArray.removeAll()
if results == nil {
return
}
for result in results! {
if let result = result as? GMSAutocompletePrediction {
self.resultsArray.append(result.attributedFullText.string)
}
}
self.searchResultController.reloadDataWithArray(self.resultsArray)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "saveAndUnwind"){
//Pushing the data to the other view controller
let destViewControllerCreateEventTable = segue.destinationViewController as! CreateEventTableViewController
destViewControllerCreateEventTable.locationAsCoords["latitude"] = self.locationAsCoords["latitude"]
destViewControllerCreateEventTable.locationAsCoords["longitude"] = self.locationAsCoords["longitude"]
destViewControllerCreateEventTable.locationAdress = self.locationAdress
destViewControllerCreateEventTable.locationLabel.text = self.locationAdress
destViewControllerCreateEventTable.locationLabel.textColor = UIColor.darkGrayColor()
}
}
}
//
import UIKit
protocol LocateOnTheMap{
func locateWithLongitude(lon:Double, andLatitude lat:Double, andTitle title: String)
}
class SearchResultsController: UITableViewController {
var searchResults: [String]!
var delegate: LocateOnTheMap!
var addNewPlaceReference = AddNewPlaceViewController()
init(view: AddNewPlaceViewController ){
super.init(style: UITableViewStyle.Plain)
addNewPlaceReference = view
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.searchResults = Array()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cellIdentifier")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.searchResults.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier", forIndexPath: indexPath)
cell.textLabel?.text = self.searchResults[indexPath.row]
return cell
}
override func tableView(tableView: UITableView,
didSelectRowAtIndexPath indexPath: NSIndexPath){
// 1
self.dismissViewControllerAnimated(true, completion: nil)
// 2
let correctedAddress:String! = self.searchResults[indexPath.row].stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.symbolCharacterSet())
let url = NSURL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)&sensor=false")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in
// 3
do {
if data != nil{
let dic = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) as! NSDictionary
let lat = dic["results"]?.valueForKey("geometry")?.valueForKey("location")?.valueForKey("lat")?.objectAtIndex(0) as! Double
let lon = dic["results"]?.valueForKey("geometry")?.valueForKey("location")?.valueForKey("lng")?.objectAtIndex(0) as! Double
// 4
self.delegate.locateWithLongitude(lon, andLatitude: lat, andTitle: self.searchResults[indexPath.row])
self.addNewPlaceReference.locationAdress = self.searchResults[indexPath.row]
self.addNewPlaceReference.locationAsCoords["latitude"] = lat
self.addNewPlaceReference.locationAsCoords["longitude"] = lon
}
}catch {
print("Error")
}
}
// 5
task.resume()
}
func reloadDataWithArray(array:[String]){
self.searchResults = array
self.tableView.reloadData()
}
}
I would like to have an autocomplete textfield that autocompletes locations for me like the one for android:
https://developers.google.com/places/training/autocomplete-android
Does anyone know where I can find a tutorial for this or an example?
Thanks!
Steps :
Add the Alamofire CocoaPods in your swift project.
Find your Google place API key on Google APIs Console.
Add following code
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let gpaViewController = GooglePlacesAutocomplete(
apiKey: "YOUR GOOGLE PLACE API KEY",
placeType: .Address
)
gpaViewController.placeDelegate = self
presentViewController(gpaViewController, animated: true, completion: nil)
}
}
extension ViewController: GooglePlacesAutocompleteDelegate {
func placeSelected(place: Place) {
println(place.description)
}
func placeViewClosed() {
dismissViewControllerAnimated(true, completion: nil)
}
}
GooglePlacesAutocomplete.swift
import UIKit
import Alamofire
enum PlaceType: Printable {
case All
case Geocode
case Address
case Establishment
case Regions
case Cities
var description : String {
switch self {
case .All: return ""
case .Geocode: return "geocode"
case .Address: return "address"
case .Establishment: return "establishment"
case .Regions: return "regions"
case .Cities: return "cities"
}
}
}
struct Place {
let id: String
let description: String
}
protocol GooglePlacesAutocompleteDelegate {
func placeSelected(place: Place)
func placeViewClosed()
}
// MARK: - GooglePlacesAutocomplete
class GooglePlacesAutocomplete: UINavigationController {
var gpaViewController: GooglePlacesAutocompleteContainer?
var placeDelegate: GooglePlacesAutocompleteDelegate? {
get { return gpaViewController?.delegate }
set { gpaViewController?.delegate = newValue }
}
convenience init(apiKey: String, placeType: PlaceType = .All) {
let gpaViewController = GooglePlacesAutocompleteContainer(
apiKey: apiKey,
placeType: placeType
)
self.init(rootViewController: gpaViewController)
self.gpaViewController = gpaViewController
let closeButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Stop, target: self, action: "close")
gpaViewController.navigationItem.leftBarButtonItem = closeButton
gpaViewController.navigationItem.title = "Enter Address"
}
func close() {
placeDelegate?.placeViewClosed()
}
}
// MARK: - GooglePlaceSearchDisplayController
class GooglePlaceSearchDisplayController: UISearchDisplayController {
override func setActive(visible: Bool, animated: Bool) {
if active == visible { return }
searchContentsController.navigationController?.navigationBarHidden = true
super.setActive(visible, animated: animated)
searchContentsController.navigationController?.navigationBarHidden = false
if visible {
searchBar.becomeFirstResponder()
} else {
searchBar.resignFirstResponder()
}
}
}
// MARK: - GooglePlacesAutocompleteContainer
class GooglePlacesAutocompleteContainer: UIViewController {
var delegate: GooglePlacesAutocompleteDelegate?
var apiKey: String?
var places = [Place]()
var placeType: PlaceType = .All
convenience init(apiKey: String, placeType: PlaceType = .All) {
self.init(nibName: "GooglePlacesAutocomplete", bundle: nil)
self.apiKey = apiKey
self.placeType = placeType
}
override func viewDidLoad() {
super.viewDidLoad()
let tv: UITableView? = searchDisplayController?.searchResultsTableView
tv?.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
}
// MARK: - GooglePlacesAutocompleteContainer (UITableViewDataSource / UITableViewDelegate)
extension GooglePlacesAutocompleteContainer: UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return places.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.searchDisplayController?.searchResultsTableView?.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
// Get the corresponding candy from our candies array
let place = self.places[indexPath.row]
// Configure the cell
cell.textLabel.text = place.description
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate?.placeSelected(self.places[indexPath.row])
}
}
// MARK: - GooglePlacesAutocompleteContainer (UISearchDisplayDelegate)
extension GooglePlacesAutocompleteContainer: UISearchDisplayDelegate {
func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String!) -> Bool {
getPlaces(searchString)
return false
}
private func getPlaces(searchString: String) {
Alamofire.request(.GET,
"https://maps.googleapis.com/maps/api/place/autocomplete/json",
parameters: [
"input": searchString,
"type": "(\(placeType.description))",
"key": apiKey ?? ""
]).responseJSON { request, response, json, error in
if let response = json as? NSDictionary {
if let predictions = response["predictions"] as? Array<AnyObject> {
self.places = predictions.map { (prediction: AnyObject) -> Place in
return Place(
id: prediction["id"] as String,
description: prediction["description"] as String
)
}
}
}
self.searchDisplayController?.searchResultsTableView?.reloadData()
}
}
}
GooglePlacesAutocomplete.xib
Hope this will help others.
Here's full updated code for Google Autocomplete place API.
Xcode 10.0 & Swift 4.2
Follow this link as to Get Google API KEY.
After Getting the API KEY
Install Cocoa Pods:
source 'https://github.com/CocoaPods/Specs.git'
target 'YOUR_APPLICATION_TARGET_NAME_HERE' do
pod 'GooglePlaces'
pod 'GooglePlacePicker'
pod 'GoogleMaps'
end
Appdelegate File:
import UIKit
import GooglePlaces
let GOOGLE_API_KEY = "AIzaSyCuZkL7bh_hIDggnJob-b0cDueWlvRgpck"
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
GMSPlacesClient.provideAPIKey(GOOGLE_API_KEY)
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
ViewController File:
import UIKit
import GooglePlaces
class ViewController: UIViewController ,CLLocationManagerDelegate{
var placesClient: GMSPlacesClient!
// Add a pair of UILabels in Interface Builder, and connect the outlets to these variables.
#IBOutlet var nameLabel: UILabel!
#IBOutlet var addressLabel: UILabel!
let locationManager = CLLocationManager()
var resultsViewController: GMSAutocompleteResultsViewController?
var searchController: UISearchController?
var resultView: UITextView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.delegate = self
if CLLocationManager.authorizationStatus() == .notDetermined
{
locationManager.requestAlwaysAuthorization()
}
placesClient = GMSPlacesClient.shared()
// self.addToNavbar()
// self.addToSubview()
self.addToPopover()
}
func addToNavbar(){
resultsViewController = GMSAutocompleteResultsViewController()
resultsViewController?.delegate = self
searchController = UISearchController(searchResultsController: resultsViewController)
searchController?.searchResultsUpdater = resultsViewController
// Put the search bar in the navigation bar.
searchController?.searchBar.sizeToFit()
navigationItem.titleView = searchController?.searchBar
// When UISearchController presents the results view, present it in
// this view controller, not one further up the chain.
definesPresentationContext = true
// Prevent the navigation bar from being hidden when searching.
searchController?.hidesNavigationBarDuringPresentation = false
}
func addToSubview(){
resultsViewController = GMSAutocompleteResultsViewController()
resultsViewController?.delegate = self
searchController = UISearchController(searchResultsController: resultsViewController)
searchController?.searchResultsUpdater = resultsViewController
let subView = UIView(frame: CGRect(x: 0, y: 65.0, width: 350.0, height: 45.0))
subView.addSubview((searchController?.searchBar)!)
view.addSubview(subView)
searchController?.searchBar.sizeToFit()
searchController?.hidesNavigationBarDuringPresentation = false
// When UISearchController presents the results view, present it in
// this view controller, not one further up the chain.
definesPresentationContext = true
}
func addToPopover(){
resultsViewController = GMSAutocompleteResultsViewController()
resultsViewController?.delegate = self
searchController = UISearchController(searchResultsController: resultsViewController)
searchController?.searchResultsUpdater = resultsViewController
// Add the search bar to the right of the nav bar,
// use a popover to display the results.
// Set an explicit size as we don't want to use the entire nav bar.
searchController?.searchBar.frame = (CGRect(x: 0, y: 0, width: 250.0, height: 44.0))
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: (searchController?.searchBar)!)
// When UISearchController presents the results view, present it in
// this view controller, not one further up the chain.
definesPresentationContext = true
// Keep the navigation bar visible.
searchController?.hidesNavigationBarDuringPresentation = false
searchController?.modalPresentationStyle = .popover
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus)
{
print(status)
}
// Add a UIButton in Interface Builder, and connect the action to this function.
#IBAction func getCurrentPlace(_ sender: UIButton) {
placesClient.currentPlace(callback: { (placeLikelihoodList, error) -> Void in
if let error = error {
print("Pick Place error: \(error.localizedDescription)")
return
}
self.nameLabel.text = "No current place"
self.addressLabel.text = ""
if let placeLikelihoodList = placeLikelihoodList {
print("placeLikelihoodList -- \(placeLikelihoodList)")
let place = placeLikelihoodList.likelihoods.first?.place
if let place = place {
self.nameLabel.text = place.name
self.addressLabel.text = place.formattedAddress?.components(separatedBy: ", ")
.joined(separator: "\n")
print(place.name)
print(place.coordinate)
print(place.placeID)
print(place.phoneNumber)
print(place.formattedAddress ?? "")
}
}
})
}
}
//MARK: Extentions
// Handle the user's selection.
extension ViewController: GMSAutocompleteResultsViewControllerDelegate {
func resultsController(_ resultsController: GMSAutocompleteResultsViewController,
didAutocompleteWith place: GMSPlace) {
searchController?.isActive = false
// Do something with the selected place.
print("Place name: \(place.name)")
print("Place address: \(String(describing: place.formattedAddress))")
print("Place attributions: \(place.attributions)")
}
func resultsController(_ resultsController: GMSAutocompleteResultsViewController,
didFailAutocompleteWithError error: Error){
// TODO: handle the error.
print("Error: ", error.localizedDescription)
}
// Turn the network activity indicator on and off again.
func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
Lightweight Solution!
Instead of using Google framework and Third party library to make simple requests I created a simple library where you can Make a number of Google api requests like Google Autocomplete, Google ReverseGeo , Place Information and Path api for getting path between two location.
To use the library all you have to do is
step-1 Import GoogleApiHelper into your project.
step-2 Initialise GoogleApiHelper
GoogleApi.shared.initialiseWithKey("API_KEY")
step-3 Call the methods
var input = GInput()
input.keyword = "San francisco"
GoogleApi.shared.callApi(input: input) { (response) in
if let results = response.data as? [GApiResponse.Autocomplete], response.isValidFor(.autocomplete) {
//Enjoy the Autocomplete Api
} else { print(response.error ?? "ERROR") }
}
You can find the library here
Using Alamofire get the autocomplete Google places result from data, you can show it in table view cell
plist configuration
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Code
import UIKit
import Alamofire
class GooglePlacesViewController: UIViewController,UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var srchLocation: UISearchBar!
#IBOutlet weak var tblLoction: UITableView!
var arrPlaces = NSMutableArray(capacity: 100)
let operationQueue = OperationQueue()
let currentLat = 51.5033640
let currentLong = -0.1276250
var LocationDataDelegate : LocationData! = nil
var tblLocation : UITableView!
var lblNodata = UILabel()
override func viewDidLoad()
{
super.viewDidLoad()
lblNodata.frame = CGRect(x: 0, y: 80, width:
self.view.frame.size.width, height: self.view.frame.size.height-60)
lblNodata.text = "Please enter text to get your location"
self.view.addSubview(lblNodata)
srchLocation.placeholder = "Ente your location details"
lblNodata.textAlignment = .center
srchLocation.delegate = self
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
self.beginSearching(searchText: searchText)
}
func beginSearching(searchText:String) {
if searchText.characters.count == 0 {
self.arrPlaces.removeAllObjects()
tblLoction.isHidden = true
lblNodata.isHidden = false
return
}
operationQueue.addOperation { () -> Void in
self.forwardGeoCoding(searchText: searchText)
}
}
//MARK: - Search place from Google -
func forwardGeoCoding(searchText:String) {
googlePlacesResult(input: searchText) { (result) -> Void in
let searchResult:NSDictionary = ["keyword":searchText,"results":result]
if result.count > 0
{
let features = searchResult.value(forKey: "results") as! NSArray
self.arrPlaces = NSMutableArray(capacity: 100)
print(features.count)
for jk in 0...features.count-1
{
let dict = features.object(at: jk) as! NSDictionary
self.arrPlaces.add(dict)
}
DispatchQueue.main.async(execute: {
if self.arrPlaces.count != 0
{
self.tblLoction.isHidden = false
self.lblNodata.isHidden = true
self.tblLoction.reloadData()
}
else
{
self.tblLoction.isHidden = true
self.lblNodata.isHidden = false
self.tblLoction.reloadData()
}
});
}
}
}
//MARK: - Google place API request -
func googlePlacesResult(input: String, completion: #escaping (_ result: NSArray) -> Void) {
let searchWordProtection = input.replacingOccurrences(of: " ", with: ""); if searchWordProtection.characters.count != 0 {
let urlString = NSString(format: "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%#&types=establishment|geocode&location=%#,%#&radius=500&language=en&key= your key",input,"\(currentLocationLatitude)","\(currentLocationLongtitude)")
print(urlString)
let url = NSURL(string: urlString.addingPercentEscapes(using: String.Encoding.utf8.rawValue)!)
print(url!)
let defaultConfigObject = URLSessionConfiguration.default
let delegateFreeSession = URLSession(configuration: defaultConfigObject, delegate: nil, delegateQueue: OperationQueue.main)
let request = NSURLRequest(url: url! as URL)
let task = delegateFreeSession.dataTask(with: request as URLRequest, completionHandler:
{
(data, response, error) -> Void in
if let data = data
{
do {
let jSONresult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:AnyObject]
let results:NSArray = jSONresult["predictions"] as! NSArray
let status = jSONresult["status"] as! String
if status == "NOT_FOUND" || status == "REQUEST_DENIED"
{
let userInfo:NSDictionary = ["error": jSONresult["status"]!]
let newError = NSError(domain: "API Error", code: 666, userInfo: userInfo as [NSObject : AnyObject])
let arr:NSArray = [newError]
completion(arr)
return
}
else
{
completion(results)
}
}
catch
{
print("json error: \(error)")
}
}
else if let error = error
{
print(error)
}
})
task.resume()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrPlaces.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let tblCell = tableView.dequeueReusableCell(withIdentifier: "locationCell")
let dict = arrPlaces.object(at: indexPath.row) as! NSDictionary
tblCell?.textLabel?.text = dict.value(forKey: "description") as? String
tblCell?.textLabel?.numberOfLines = 0
tblCell?.textLabel?.sizeToFit()
return tblCell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
if LocationDataDelegate != nil
{
let dict = arrPlaces.object(at: indexPath.row) as! NSDictionary
print(dict.value(forKey: "terms") as! NSArray)
let ArrSelected = dict.value(forKey: "terms") as! NSArray
LocationDataDelegate.didSelectLocationData(LocationData: ArrSelected)
}
self.dismiss(animated: true, completion: nil)
}
}
class AddNewAddressVC: UIViewController,UITextFieldDelegate{
func autocompleteClicked() {
let autocompleteController = GMSAutocompleteViewController()
autocompleteController.delegate = self
// Specify the place data types to return.
let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.name.rawValue) |
UInt(GMSPlaceField.placeID.rawValue))!
autocompleteController.placeFields = fields
// Specify a filter.
let filter = GMSAutocompleteFilter()
filter.type = .address
autocompleteController.autocompleteFilter = filter
// Display the autocomplete view controller.
present(autocompleteController, animated: true, completion: nil)
}
#IBAction func action_selectGooglePlaces(_ sender: UIButton) {
autocompleteClicked()
}
}
extension AddNewAddressVC: GMSAutocompleteViewControllerDelegate {
// Handle the user's selection.
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
print("Place name: \(place.name)")
print("Place ID: \(place.placeID)")
print("Place attributions: \(place.attributions)")
dismiss(animated: true, completion: nil)
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
// TODO: handle the error.
print("Error: ", error.localizedDescription)
}
// User canceled the operation.
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
dismiss(animated: true, completion: nil)
}
// Turn the network activity indicator on and off again.
func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
I've got JSON filling my UITableView successfully, but the JSON is often updated so I need the ability to refresh. I followed THIS TUTORIAL to implement a pull to refresh control. Visually, it seems like it all works correctly, but when I call tableView.reloadData() the table doesn't reload. However, if I leave the ViewController and return, the table is updated. Why would tableView.reloadData() work in viewDidAppear and viewWillAppear but not in my custom refresh() function?
MainVC.swift file
class MainVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableView: UITableView!
var dataArray: NSArray = NSArray()
#IBOutlet var Controller: UISegmentedControl!
var refreshControl:UIRefreshControl!
func refresh(sender:AnyObject)
{
refreshBegin("Refresh",
refreshEnd: {(x:Int) -> () in
self.tableView .reloadData()
println("Table Reloaded")
self.refreshControl.endRefreshing()
})
}
func refreshBegin(newtext:String, refreshEnd:(Int) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
println("refreshing")
sleep(2)
dispatch_async(dispatch_get_main_queue()) {
refreshEnd(0)
}
}
}
override func viewWillAppear(animated: Bool) {
self.tableView .reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.titleView = UIImageView(image: UIImage(named: "logojpg.jpg"))
startConnectionAt("http://www.domain.com/json.php")
refreshControl = UIRefreshControl()
refreshControl.backgroundColor = UIColor.orangeColor()
refreshControl.tintColor = UIColor.whiteColor()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to Refresh")
refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
tableView.addSubview(refreshControl)
}
//MARK: JSON Loading
var data: NSMutableData = NSMutableData()
func startConnectionAt(urlPath: String){
var url: NSURL = NSURL(string: urlPath)
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)
connection.start()
}
func connection(connection: NSURLConnection!, didFailWithError error: NSError!) {
println("Connection failed.\(error.localizedDescription)")
}
func connection(connection: NSURLConnection, didRecieveResponse response: NSURLResponse) {
println("Recieved response")
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
self.data = NSMutableData()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
self.data.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
var dataAsString: NSString = NSString(data: self.data, encoding: NSUTF8StringEncoding)
var err: NSError
var json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
var results: NSArray = json["needs"] as NSArray
self.dataArray = results
tableView.reloadData()
println("success")
}
//End loading of JSON
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.dataArray.count;
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell:CustomCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as CustomCell
var rowData: NSDictionary = dataArray[indexPath.row] as NSDictionary
var firstName=rowData["needFirstname"] as String
var descrip=rowData["needDescription"] as String
var poster=rowData["needPoster"] as String
var city=rowData["needCity"] as String
var state=rowData["needState"] as String
var country=rowData["needCountry"] as String
cell.needFirstName.text = firstName
cell.needDescription.text = descrip
cell.needDescription.numberOfLines = 0
cell.needPoster.text = poster
cell.needCity.text = city
cell.needState.text = state
cell.needCountry.text = country
return cell
}
#IBAction func Change(sender: AnyObject) {
if Controller.selectedSegmentIndex == 0 {
startConnectionAt("http://www.domain.com/localJSON.php")
}
else if Controller.selectedSegmentIndex == 1 {
startConnectionAt("http://www.domain.com/intlJSON.php")
}
self.tableView .reloadData()
}
}
Your last comment is right-on in my view.
During your pull to refresh function, you call tableView.reloadData(), however, reloadData() does not inherently do any repopulating the elements in the data source (in your case, dataArray). It simply reloads all the data that's currently in the table view's data source at the time it is called.
So my recommendation would be to construct your refresh function such that the following happens:
Initiate a request to your web service.
When the response comes back (ie, connectionDidFinishLoading is executed), parse the JSON results and assign that result to the dataArray instance. You seem to be doing this already in connectionDidFinishLoading, so it's just a matter of sending the request to your web service, I'd think.
Call tableView.reloadData() to display any new elements that have been added since the last time the tableView's data was displayed. Again, you're doing this already in connectionDidFinishLoading, so #1 is the primary thing that I think needs to happen.
Referring to https://stackoverflow.com/a/25957339
Not sure but maybe the connection is run on a different thread, if so you need to run the table update on the main UI thread
// using Swift's trailing closure syntax:
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}