-2

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.

Ghanshyam Tomar
  • 762
  • 1
  • 8
  • 24
Mit
  • 1
  • 2

1 Answers1

0

Well, your code needs lot of changes. Let me give you some suggestions.

  1. Instead of self.tableView.insertSubview(refreshControl, atIndex: 0) try to use tableView.addSubview(refreshControl). Look thedifference between add and insert subview here

  2. Define another function to populate view. Eg. func populateView()

  3. Replace self.handleRefresh() with self.populateView()

  4. Replace

    self.refreshControl.addTarget(
        self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged
    ) 
    

    with

    self.refreshControl.addTarget(
        self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged
    )
    
  5. 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.

  1. Why its not working in other view?

    Its because in UITableViewController refreshControl comes pre-fit, a regular ViewController does not.

  2. 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
    }()
    
  3. In viewDidLoad() add UIRefreshControl as a subview to the tableView as: self.tableView.addSubview(self.refreshControl)

Hope this helps you to understand!

Community
  • 1
  • 1
Boopathy
  • 415
  • 3
  • 12
  • Ok Boopathy, this night i try to replace your suggested changes, but why my code work well on other Views? – Mit May 26 '15 at 12:13
  • Mit, i have edited the answer. Check it and do let me know if it helps you. Happy coding! – Boopathy May 26 '15 at 17:54
  • Hi Boopathy, i've try your solution, but result is the same. Using my code i've successfully create a tableView with refreshControl. The views where my code works are equal to one in which not working . All contain tableView view and are simple UIViewController , not UITableViewController. It could be a problem due to some parameter in the storyboard that differs between the views ? – Mit May 26 '15 at 21:59