mardi 4 août 2015

In Swift, how can I get an NSDate from a dispatch_time_t?

"Walltime" is a little-known time format used by Grand Central Dispatch. Apple talks about it here:

http://ift.tt/1HnSNLW

There are some things it's really handy for, though, but it's a sticky wicket. It's hard to make it play nice with other time formats, which is what my question's about.

I can make a walltime by turning an NSDate into a timespec, and then using with dispatch_walltime:

 let now = NSDate().timeIntervalSince1970
 let nowWholeSecsFloor = floor(now)
 let nowNanosOnly = now - nowWholeSecsFloor
 let nowNanosFloor = floor(nowNanosOnly * Double(NSEC_PER_SEC))
 var thisStruct = timespec(tv_sec: Int(nowWholeSecsFloor),
 tv_nsec: Int(nowNanosFloor))
 let wallTime = dispatch_walltime(& thisStruct, 0)

But lord love a duck, I can't figure out how to get it back into an NSDate. Here's my try:

public func toNSDate(wallTime: dispatch_time_t)->NSDate {
    let wallTimeAsSeconds = Double(wallTime) / Double(NSEC_PER_SEC)
    let date = NSDate(timeIntervalSince1970: wallTimeAsSeconds)
    return date
}

The resulting NSDate is not just off, but somewhat hilariously off, like five hundred years or something. As Martin R pointed out, the problem is that dispatch_time_t is an opaque value, with an undocumented representation of time.

Does anyone know how to do this?

EDIT: if the process of creating the walltime is confusing, this is basically what's going on:

NSDate defines time with a Double, and everything after the decimal point is the nanoseconds. dispatch_time, which can create a walltime, defines time with UInt64, so you have to convert between Double and UInt64 to use it. To do that conversion you need to use a timespec, which takes seconds and nanoseconds as separate arguments, each of which must be Int.

A whole lotta convertin' going on!



via Chebli Mohamed

Obj-c method with nullable return value not properly converting to swift

I have a problem where the following OBJ-C method will not translate to Swift with optional return value:

- (nullable id)executeRequest:(ServerRequest *)request returningResponse:(__nullable NSURLResponse **__nullable)responseRef errorRef:(NSError **)errorRef

When trying to override that method in a swift class it translates to this:

override func executeRequest(request: ServerRequest, returningResponse responseRef: AutoreleasingUnsafeMutablePointer<NSURLResponse?>) throws -> AnyObject

Note that the return value is AnyObject instead of AnyObject?

What am I doing wrong here? I'm using X-Code 7 Beta 3



via Chebli Mohamed

GCM extension for AIR on ios?

Is the an extension for using GCM on AIR project in ios?

I know GCM works on ios native http://ift.tt/1f8Y8Rq

but I need it to work on Adobe Air



via Chebli Mohamed

How to plot the route in Ios when user walikng or driving along the road using Google Maps SDK

Hi i am beginner for using Google maps in Ios and i my project i am trying to plot the route when user walking or driving along the road but here current location is getting but route is not plotting when user walking laong road if any body know about this please help me

My code below:-

#import "ViewController.h"

@interface ViewController ()
{
    GMSMapView *_mapView;
    NSMutableArray *_coordinates;
    LRouteController *_routeController;
    GMSPolyline *_polyline;
    GMSMarker *_markerStart;
    GMSMarker *_markerFinish;
    CLLocationManager *locationManager_;
}

@end

@implementation ViewController

- (void)viewDidLoad{

    [super viewDidLoad];

    _markerStart = [[GMSMarker alloc]init];
    _markerFinish = [[GMSMarker alloc]init];

    _coordinates = [[NSMutableArray alloc]init];

    locationManager_ = [[CLLocationManager alloc] init];
    locationManager_.delegate = self;
    [locationManager_ setDistanceFilter:10.0f];
    locationManager_.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager_ requestAlwaysAuthorization];
    [locationManager_ startUpdatingLocation];
 }

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{

    _polyline.map = nil;
    _markerStart.map = nil;
    _markerFinish.map = nil;

    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:newLocation.coordinate.latitude
                                                            longitude:newLocation.coordinate.longitude
                                                                 zoom:16];

    _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
    _mapView.myLocationEnabled = YES;
    _mapView.settings.myLocationButton = YES;
    self.view = _mapView;

    _markerStart.position = CLLocationCoordinate2DMake(newLocation.coordinate.latitude, newLocation.coordinate.longitude);
    _markerStart.title = @"CurrentLocation";
    _markerStart.snippet = @"Hello";
    _markerStart.map = _mapView;

    _markerFinish.title = @"Finish";
    _markerFinish.snippet = @"End";
    _markerFinish.map = _mapView;

    NSLog(@"didUpdateToLocation: %@", newLocation);
    NSLog(@"new location %f",newLocation.coordinate.latitude);
    NSLog(@"new location %f",newLocation.coordinate.longitude);

    [_coordinates addObject:[[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude]];

    NSLog(@"array list %lu",(unsigned long)_coordinates.count);

    if ([_coordinates count] > 1)

    {
        NSLog(@"1");

        [_routeController getPolylineWithLocations:_coordinates travelMode:TravelModeDriving andCompletitionBlock:^(GMSPolyline *polyline, NSError *error) {

            if (error)
            {
                NSLog(@"%@", error);
            }

            else if (!polyline)
            {
                NSLog(@"No route");
                [_coordinates removeAllObjects];
            }

            else
            {
                _markerStart.position = [[_coordinates objectAtIndex:0] coordinate];
                _markerStart.map = _mapView;
                _markerFinish.position = [[_coordinates lastObject] coordinate];
                _markerFinish.map = _mapView;

                _polyline = polyline;
                _polyline.strokeWidth = 3;
                _polyline.strokeColor = [UIColor redColor];
                _polyline.map = _mapView;
            }
        }];
    }
}

@end

But route is not plotting please help me some one



via Chebli Mohamed

Deleting all rows from UITableView

I keep running into an assertion failure but I am not sure how to resolve.

Initially I did a proof of concept app to understand how this functions and had this code in it:

if (self.arrNonATIResults.count > 0) {
        NSMutableArray* arrIndexPaths = [NSMutableArray array];
        for(int i=0; i<[self.arrNonATIResults count]; i++) {
            NSIndexPath *anIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
            [arrIndexPaths addObject:anIndexPath];
        }

        [self.accountTable beginUpdates];
        [self.accountTable deleteRowsAtIndexPaths:arrIndexPaths  withRowAnimation:UITableViewRowAnimationTop];
        self.arrNonATIResults = [NSMutableArray array];
        [self.accountTable endUpdates];
    }

It worked fine. Moving that code into my app I ran into this assertion failure:

Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (0) must be equal to the number of rows contained in that section before the update (3), plus or minus the number of rows inserted or deleted from that section (0 inserted, 2 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).

Here's where I am getting confused, self.arrNonATIResults (the table datasource) contains two objects (it's hardcoded) - so the table has only two rows. Where is the 3rd row in the error message coming from? I did read that if you remove all rows then you also have to remove the section as well. Is that the third item in the error message?

So I rewrote my initial code but this still shouldn't work because the arrIndexPath array is only going to include 2 NSIndexPaths. Can anyone point me in the right direction as to what I am doing wrong?

   - (void) clearNonATITable {

        if (self.arrNonATIResults.count > 0) {

            NSMutableArray* arrIndexPaths = [NSMutableArray array];
            for(int i=0; i<[self.arrNonATIResults count]; i++) {
                NSIndexPath *anIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
                [arrIndexPaths addObject:anIndexPath];
            }


            [self.accountTable beginUpdates];

            for (int i=0; i<arrIndexPaths.count; i++) {

                NSIndexPath* thisIndexPath = [arrIndexPaths objectAtIndex:i];

                if (self.arrNonATIResults.count > 0) {
                    [self.accountTable deleteRowsAtIndexPaths:[NSArray arrayWithObjects:thisIndexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
                    [self.arrNonATIResults removeObjectAtIndex:0];
                } else {
                    NSIndexSet* setIndexSections = [[NSIndexSet alloc] initWithIndex:thisIndexPath];
                    [self.accountTable deleteSections:setIndexSections withRowAnimation:UITableViewRowAnimationFade];
                }
            }

            [self.accountTable endUpdates];

        }
    }




via Chebli Mohamed

Is it possible to add view behind navigation bar in UITableViewController

I wonder if its possible to add a view under the navigation bar in a UITableViewController?

What I would like to do is to add a view under the navigation bar in my UITableViewController so that I can add a search input / filter button to that view. But I want the view to have a fixed position under the navigation bar so that I can hide the navigationbar+view when swiping.

Right now storyboard only lets me add a view in the UITableViewController. And the new view is also swipeable. And the loading indicator shows up above the view when you swipe down.

enter image description here



via Chebli Mohamed

Swift tableView.reloadData() is not working

I am new to Swift, I need to reload my records when I click on the UIButton action. For me reload method is stop working. I tried in all the possible ways as following:

Here is the function that I call when I tap the button

@IBAction func refresh(sender: AnyObject) {

    // I tried this one but doesn't works

    dispatch_async(dispatch_get_main_queue()) {
        self.tblNotes.reloadData()
    }

    // This one too doesn't works for me
        self.tblNotes.reloadData()

    //Neither this
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.tblNotes.reloadData()
    })     

}

Below one is my entire Class

class ListaTrmTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate , UISearchDisplayDelegate, EditNoteViewControllerDelegate {


@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet var tblNotes: UITableView!

var arrNotes: Array<CKRecord> = []
var editedNoteRecord: CKRecord!
var selectedNoteIndex: Int!

var searchActive : Bool = false
var filtered:Array<CKRecord> = []

var notesArray = [ListaTrmTableViewController]()


override func viewDidLoad() {
    super.viewDidLoad()

    tblNotes.delegate = self
    tblNotes.dataSource = self
    searchBar.delegate = self

        fetchNotes()
}

 override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

 func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // Return the number of sections.
    return 1
}

 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // Return the number of rows in the section.
    if(searchActive) {
        return filtered.count
    }

    return arrNotes.count
}
//Cell height size
 func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 50.0
}

 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    selectedNoteIndex = indexPath.row
    performSegueWithIdentifier("viewControllerSg", sender: self)
}

//Segue to other ViewController
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "viewControllerSg" {
        let editNoteViewController = segue.destinationViewController as! ViewController

        if let index = selectedNoteIndex {
            editNoteViewController.editedNoteRecord = arrNotes[index]
        }
        if(searchActive){
            editNoteViewController.editedNoteRecord = filtered[selectedNoteIndex]
        }
    }
}

// Retrive data from CloudKit

func fetchNotes() {
  let container = CKContainer.defaultContainer()
    let privateDatabase = container.publicCloudDatabase
    let predicate = NSPredicate(value: true)

    let query = CKQuery(recordType: "Notes", predicate: predicate)
    query.sortDescriptors = [NSSortDescriptor(key: "Title", ascending: true)]

    privateDatabase.performQuery(query, inZoneWithID: nil) { (results, error) -> Void in
        if error != nil {
            println(error)
        }
        else {
            println(results)

            for result in results {
                self.arrNotes.append(result as! CKRecord)
            }

            NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                self.tblNotes.reloadData()
                self.tblNotes.hidden = false
            })
        }
    }
}


func didSaveNote(noteRecord: CKRecord, wasEditingNote: Bool) {
    if !wasEditingNote {
        arrNotes.append(noteRecord)
    }
    else {
        arrNotes.insert(noteRecord, atIndex: selectedNoteIndex)
        arrNotes.removeAtIndex(selectedNoteIndex + 1)
        selectedNoteIndex = nil
    }


    if tblNotes.hidden {
        tblNotes.hidden = false
    }

    tblNotes.reloadData()
}


 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("idCellNote", forIndexPath: indexPath) as! UITableViewCell

    if(searchActive){
        let noteRecord: CKRecord = filtered[indexPath.row]
        cell.textLabel?.text = noteRecord.valueForKey("Atitulo") as? String
    } else {
        let noteRecord: CKRecord = arrNotes[indexPath.row]
        cell.textLabel?.text = noteRecord.valueForKey("Atitulo") as? String
    }

    return cell
}

// Search functions

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    searchActive = true;
}

func searchBarTextDidEndEditing(searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    searchActive = false;
}

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

    filtered = arrNotes.filter ({ (note) -> Bool in
        let titles = note.objectForKey("Atitulo") as? String
        //proceed as per normal
        let range = titles!.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)

        // I returned false to isolated the problem
        if let range = range { return true} else { return false}
    })
    if(filtered.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }
    self.tblNotes.reloadData()
}

// The big problem is here

@IBAction func refresh(sender: AnyObject) {

    // I tried this one but don't works

    dispatch_async(dispatch_get_main_queue()) {
        self.tblNotes.reloadData()
    }
    // This one don't works too
        self.tblNotes.reloadData()

    //Neither this
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.tblNotes.reloadData()
    })     

}



via Chebli Mohamed