mardi 4 août 2015

Anyone else's Xcode 6.4 crashing after El Capitan beta 6?

I updated my computer to the latest beta that was released to developers last night and the same project that was compiling fine yesterday night now fails due to a supposed .xib/.storyboard error.

I have tried cleaning the project, downloading a previous version off of github, etc.. and yet the project still gives me the following error. "Failed to communicate with Interface Builder" as well as Command /Applications/http://ift.tt/1cExCL8 failed with exit code 255. Literally nothing was changed with the .storyboard file or anything remotely related to it.

What's more is that trying to open any .xib/.storyboard file (even the launch screen xib which I haven't touched leads to Xcode crashing which leads me to think this has nothing to do with me.)

Anyone else experiencing this? Any advice or temporary fixes?

Update: Trying to run anything on the simulator causes it to crash continuously or hang with the following error message: "Springboard quit unexpectedly"

Update 2: Playgrounds are unusable but do not crash. Also, these lads seem to be in the same boat as we are. http://ift.tt/1IE4Wxs

This is why we can't have nice things, Apple.



via Chebli Mohamed

AFNetworking caching using ETag

I have problem implementing caching using AFNetworking and ETag values. My server returns Cache-Control and ETag headers values for every request. But if I make a second request for the same resource AFNetworking won't add ETag. Should I manually save etag for each response I got and append it to next requests?

In app delegate I have set cache object:

 NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:20 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];
 [NSURLCache setSharedURLCache:URLCache];

Also, I'm using default cache policy of AFHTTPRequestSerializer.

Any ideas what is the problem? Maybe I don't understand the idea of http caching. As far as I know it should be transparent, and all I have to do is to attach ETag and Cache-Control headers for every response.



via Chebli Mohamed

In app purchase not working after publishing iOS app to App Store

During development I've created test accounts which are able to obtain the price of the in app purchase as well as actually purchasing it without an issue. However after publishing the iOS app to App Store, the version of the app in App store can't even retrieve price of the product, and nothing shows up when I press the button to send the purchase request.

Uninstalling the app and redeploy the development version to the same device got it to work again.

What could be the problem? Is there a way to debug or see logs on the app store downloaded version? (iOS noob here)

Thanks!



via Chebli Mohamed

Auto-layout issue on scroll

I have .xib which has some auto-layout like so (might need to click to zoom): enter image description here

Nothing special, I have 13px spacing with the border of the superview. This xib is then loaded in the code into a tableViewCell.

I'm also setting the height in the viewDidLoad of the table like so:

[self.tableView setEstimatedRowHeight:40];
[self.tableView setRowHeight:UITableViewAutomaticDimension];

Now the fun begins. The auto-layout works when it wants to, and sometimes I scroll a cell out of view, bring it back and it's not the same size. See image below: enter image description here

Any ideas on what I am doing wrong?

PS: Not in the screengrab here, but I do have some cells with a lot of text that look like the same height of the big cell on left.



via Chebli Mohamed

Annotation pins and detail view from sqlite in Xcode

I've been looking around the internet to find a tutorial or something to explain this:
I need to show some pins on a map. I need to get them from a sqlite database (table with POI's name, lat, lon, and some text). They have to show annotations callouts with title and subtitle and open their detail views. All that with Xcode and Objective-C. How can I do that? Can anybody help and write the code?



via Chebli Mohamed

iOS autolayout issue

i am using xcode 6.4. i have a view controller named "sample".The view controller contain a scroll view.The scrollview contain another view(container view).The width of container view is thrice of the width of scrollview.when the scroll view is swiping right(or left) it must show the 3 parts of the container view.I did it using paging enabled property of UIscrollview(without auto-layout).But when using auto-layout i cant find a solution.Can anybody tell me a solution for this???please explain constraints for scroll view and container view.Can anybody upload a demo???



via Chebli Mohamed

Progress View and sound with Swift [on hold]

I have a mp3 file in the Supporting Files folder. I can make it play and stop. I put a Progress View from the Object Library to the Main.storyboard, but how to make the Progress View show the progress of the sound when the sound plays?

I would much appreciate if someone could introduce me to the more basics. (I am very new, any simple explanation will help)

var sound1 = AVAudioPlayer()
@IBOutlet var progress: UIView!

@IBAction func play(sender: AnyObject) {
    sound1.play()

}



via Chebli Mohamed

Cannot unpause game when bringing app back to Foreground

My SpriteKit game is automatically paused when the app goes into the background. I'm trying to un-pause the game in the appropriate application events, to no avail. I'm manually un-pausing the two SKViews and the game Scene that constitute the app. From inside the AppDelegate file:

func applicationWillEnterForeground(application: UIApplication) {

    if let vw = self.window?.rootViewController {
        let gc = vw as! GameViewController
        let parView = gc.view as! SKView
        parView.paused = false
        gc.gameView.paused=false
        gc.gameScene.paused=false
        println("paused = \(gc.gameScene.paused)")

    }

}

func applicationDidBecomeActive(application: UIApplication) {

    if let vw = self.window?.rootViewController {
        let gc = vw as! GameViewController
        let parView = gc.view as! SKView
        parView.paused = false

        gc.gameView.paused=false
        gc.gameScene.paused=false
        println("paused = \(gc.gameScene.paused)")

    }

}

At the end I print the pause state. If I hit the device's Home key and then return to the app, it prints false as desired. However, somewhere (not by my code) this is being immediately set back to true, and the game remains paused.



via Chebli Mohamed

Swift AVPlayer has no done button

Using iOS 8.4, I have created an AVPlayerViewController with and AVPlayer. The video controls appear as expected and the video plays, but there is no "Done" button and xCode crashes whenever I try to lay one on the ViewController at the top of the view. An example I saw: Video Playback clearly shows a "Done" button on the upper left of the screen.

Do AVPlayerViewController and AVPlayer support a "Done" button? Is it possible to add one?



via Chebli Mohamed

what is typedef long dispatch_once_t in objective c [duplicate]

This question already has an answer here:

i was going through this tutorial, and i noticed they used:

typedef long dispatch_once_t

yet they did not explain what it does. Furthermore, I have no idea what does "typedef long" mean ? i tried searching through references but didnt find an answer. Can you provide an example of how typedef long works ?



via Chebli Mohamed

How to know which SKSpriteNode is affected by collision detection in Swift?

Situation: I have two or more ships on my iOS screen. Both have different attributes like name, size, hitpoints and score points. They are displayed as SKSpriteNodes and each one has added a physicsBody.

At the moment those extra attributes are variables of an extended SKSpriteNode class.

import SpriteKit    
class ship: SKSpriteNode {
            var hitpoints: Int = nil?
            var score: Int = nil?

        func createPhysicsBody(){
            self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width / 2)
            self.physicsBody?.dynamic = true
            ...
        }
    }

In this 'game' you can shoot at those ships and as soon as a bullet hits a ship, you get points. 'Hits a ship' is detected by collision.

func didBeginContact(contact: SKPhysicsContact){    
    switch(contact.bodyA.categoryBitMask + contact.bodyB.categoryBitMask){
        case shipCategory + bulletCategory:
            contactShipBullet(contact.bodyA, bodyB: contact.bodyB)
            break;
        default:
            break;
    }
}

Problem: Collision detection just returns a physicsBody and I do not know how to get my extended SKSpriteNode class just by this physicsBody.

Thoughts: Is it a correct way to extend SKSpriteNode to get my objects like a ship to life? When I add a ship to my screen it looks like:

var ship = Ship(ship(hitpoints: 1, score: 100), position: <CGPosition>)
self.addChild(ship)

Or is this just a wrong approach and there is a much better way to find out which object with stats so and so is hit by a bullet thru collision detection?

This question is similar to my other question - I just want ask this in broader sense.



via Chebli Mohamed

How can I create a cv:Mat from UIImage/NSData?

I'm working on image recognition for our company app (iOS).

Initially what I wanted to do is: to make a photo of some digits number and try to use recognition library tesseract. The problem is: the tesseract doesn't work good enough for me. So I decided to use image recognition instead of text recognition library.

I've made pictures of numbers from 0 to 9 with the font I need with the background I need. Next I take a photo of a number (which consists of several digits). Then I wanna compare the digits to the pictures I've made. The algorithm I've found on the internet. The problem is: I have to create a cv::Mat object for the photo, which I've taken in order to make a comparison. I'm working with iOS (Objective-C), so the image object is UIImage. How can I convert the UIImage to the cv::Mat object ?

I need somehow to decode the NSData object to the cv::Mat (the NSData object I can get from the following code, where testedImage is the UIImage*)

NSData *testedImageData = UIImagePNGRepresentation(testedImage);

The only way I can do it now is to save the picture on the file system and then get it's path and create a cv::Mat object, but it's not a good idea ...



via Chebli Mohamed

JSON parsing using [NSJSONSerialization JSONObjectWithData:dataJson options:0 error:&error] thowing nil

error = Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0x7fa4e25da7c0 {NSDebugDescription=Garbage at end.}

If changing NSData to NSString , response is getting but using

id jsonData = [NSJSONSerialization JSONObjectWithData:dataJson options:0 error:&error]

showing above error, and response nil.



via Chebli Mohamed

View is presented modally instead of Show

So I have a TableViewController. When a cell is tapped, a showEpisodes segue is called. This segue is set as Show and pointed to a Navigation Controller, like this:

Segue

The problem is that my view shows modally, i.e it doesn't have a navigationcontroller.

Here is the code I use in Main Table View Controller

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath)
    self.performSegueWithIdentifier("showEpisodes", sender: cell?.textLabel?.text)

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showEpisodes" {
        let viewController = segue.destinationViewController as! UINavigationController
        let vc = viewController.topViewController as! EpisodesTableViewCOntroller
        let indexPath: NSIndexPath = self.tableView.indexPathForSelectedRow!
        let object: PFObject = self.objectAtIndexPath(indexPath)!
        vc.podcast = object
       // self.navigationController!.pushViewController(vc, animated: true)
    }

}

If I uncomment the self.navigationController!.pushViewController(vc, animated: true) part, the view will get pushed fine but as soon as it is loaded, a black window is modally presented over it. I've checked the UI Hierarchy in the debugger without success. Any ideas please?



via Chebli Mohamed

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

How to force or disable interface orientation for some but not all UIViewController?

I have an app with 9-10 screens. I embedded a UINavigationController into my view controller. I have few view controllers which I want set only portrait orientation: it means that rotating the device should not rotate these view controllers to landscape mode. I have tried the following solutions:

first:

   NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
   [[UIDevice currentDevice] setValue:value forKey:@"orientation"];

but screen still rotates to landscape.

Second: I created a custom view controller class as PortraitViewController and added the code below in PortraitViewController.m

@interface PortraitViewController ()
@end

@implementation PortraitViewController
- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    //Here check class name and then return type of orientation
    return UIInterfaceOrientationMaskPortrait;
}
@end

After that I implemented PortraitViewController.h as a base class

#import <UIKit/UIKit.h>
#import "PortraitViewController.h"
@interface Login : PortraitViewController
@end

It does not work at all, still allows view controller to rotate in landscape mode.

Is there any other solution i am using iOS 8 & don't want viewcontroller to rotate in landscape mode?

EDIT: Is it possible to have Landscape orientation only for some view controllers, and force other view controllers orientation to stick to Portrait?



via Chebli Mohamed

How to make an iOS App recognize a number as a phone number

I am creating an iOS application using the Apache Cordova tools for Visual Studio and I am trying to find a way to make my application recognize a user-inputted number as a phone number.

The app deals with calling drivers and cabs and allows the users to enter the drivers' numbers but has a pre-determined, hard coded list of the cab numbers included as well. When i open the app, the hard coded numbers show up blue and with a hyperlink to them with the standard phone options iOS menu but the numbers the users input into a table don't turn blue immediately after they are entered, you either have to back out of the app and come back in, or calling one of the cab numbers and backing out of the call also enables the blue hyperlink.

Is there a tag i can attach to or a method i can call to make the app recognize that these numbers are phone numbers? Or is there a certain refresh call that would reload the data and automatically make these inputted numbers attached to a hyperlink like the hard coded numbers?



via Chebli Mohamed

-[AXSpeechAction retain]: message sent to deallocated instance 0x1c37e2b0

I am using the AVSpeechSynthesizer() in Swift for reading some directions and heading instructions for visually impaired users.

Yet, after some time the app crashes with:

-[AXSpeechAction retain]: message sent to deallocated instance 0x1c37e2b0.

Of course that class is not included in my project and i do not even know who creates and removes it.



via Chebli Mohamed

viewdidload called after closing dismissing child viewcontroller

I have a main Viewcontroller and a Child Viewcontroller.

I realized that when closing the Childviewcontroller like:

        self.dismissViewControllerAnimated(true, completion: {
            self.dismissViewControllerAnimated(true, completion: nil);
        });

it will just dismiss the child viewcontroller and I can see the mainview controller. No other code is processed

if I close the child viewcontroller with a notification to the main viewcontroller :

                self.dismissViewControllerAnimated(true, completion: {
                    NSNotificationCenter.defaultCenter().postNotificationName("refreshtextviewer_with_bookmark", object: nil);
                    self.dismissViewControllerAnimated(true, completion: nil);

                });

then my refreshtextviewer_with_bookmark() function is called in the main viewcontroller and in parallel the standard viewDidLoad() is also called.

Is it normal behaviour, that in this case the viewDidLoad() is called after dismissing the child viewcontroller ? Is there a way to prevent this ?



via Chebli Mohamed

PFObject Subclass Not Loading Objective-C

I'm running into some trouble with a PFObject subclass. I've gone thru all of the proper setup (registering the subclass in the delegate, setting the class name, etc). But for some reason I can't get the object to load without crashing it in the view that it's supposed to be loading in.

Passing the Object

if ([segue.identifier isEqualToString:@"toPostView"])
{
    pbPostViewController *postView = [pbPostViewController new];
    postView = (pbPostViewController *)segue.destinationViewController;
    [postView setPostToLoad:_selectedPost];
}

Receiving View.h

//  Copyright (c) 2015 Chris Culos. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import "PALongTextView.h"
#import "pbPost.h"

@interface pbPostViewController : UIViewController

@property (strong, nonatomic) pbPost *postToLoad;

Receiving View.m

#import "pbPost.h"

@interface pbPostViewController ()

@end

@implementation pbPostViewController

- (void)viewDidLoad {

    pbPost *post = [pbPost postWithObject:_objectToLoad];
    NSLog(@"post: %@", post);


//    _timeStampLabel.text      = post.postTimeStamp;
    _userNameLabel.text       = [post.postOwner valueForKey:@"username"];
    _profileImage.image       = [post.postOwner valueForKey:@"profileImage"];
    _postDescriptionView.text = post.postDescriptionString;
    _bookmarkCounterLabel.text= [NSString stringWithFormat:@"%li bookmarks", post.postBookmarkedArray.count];
    _postContentView.text     = @"POST CONTENT PAGE 123 456 ETC ETC ETC";


    [super viewDidLoad];
    //

pbPost.h

@interface pbPost : PFObject <PFSubclassing>
{

}
@property (nonatomic, retain) NSDate *postTimeStamp;
@property (nonatomic, retain) NSString *postDescriptionString;
@property (nonatomic, retain) NSString *postContentString;
@property (nonatomic, retain) NSString *postBookmarkString;
@property (nonatomic, retain) NSString *postPageCounterString;
@property (nonatomic, retain) NSArray  *postBookmarkedArray;
@property (nonatomic, retain) PFFile   *postOwnerProfileImage;

@property (nonatomic, retain) NSNumber *postFontSize, *totalPages;

@property (nonatomic, retain) PFUser *postOwner;

+ (pbPost *) postWithObject: (PFObject *)object;

pbPost.m

@implementation pbPost

@dynamic postContentString, postBookmarkString, postDescriptionString, postPageCounterString, postTimeStamp, commentTableView, commentButton, bookMarkButton, postOwnerProfileImage, optionsButton, postFontSize, totalPages, postBookmarkedArray, postOwner;

+ (void)load
{
    [self registerSubclass];
}

+ (NSString *)parseClassName
{
    return @"userPosts";
}

+ (pbPost *) postWithObject: (PFObject *)object
{
//    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
//    [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
//    [dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

    pbPost *post               = [pbPost postWithObject:object];

    [post fetchInBackgroundWithBlock:^(PFObject *object, NSError *error) {
        if (!error) {
            post.postTimeStamp         = [object valueForKey:@"createdAt"];
            post.postDescriptionString = [object valueForKey:@"titleSummary"];
            post.postFontSize          = [object valueForKey:@"fontSize"];
            post.postContentString     = [object valueForKey:@"postContent"];
            post.totalPages            = [object valueForKey:@"numPages"];
            post.postBookmarkedArray   = [object valueForKey:@"bookmarkedBy"];
            post.postOwner             = [object valueForKey:@"postOwner"];
            post.postOwnerProfileImage = [post.postOwner valueForKey:@"profileImage"];

            NSLog(@"LOAD THE THING!: %@", post);
        }
        else

        {
            NSLog(@"Error Loading Post: %@", error);
        }
    }];




    return post;
}

Under this circumstance; I'm getting an EXC_BAD_ACCESS at + (pbPost *)postWithObject:(PFObject *)object in the implementation file.

I feel like I'm missing something very simple here; what can it be? Thanks in advance for your help again everyone! This has stumped me for a little while and I need to get some outside help.



via Chebli Mohamed

Different coordinates while resizing an imageview iOS

I'm trying to resizing an imageview using these functions:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch* mTouch = [touches anyObject];
    if (mTouch.view == [self Logo_01]) {
        CGPoint cp = [mTouch locationInView:[self view]];
        [[mTouch view]setCenter:CGPointMake(cp.x-xd, cp.y-yd)];
        NSLog(@"questo è x");
        NSLog(@"lalal %f", cp.y);

        if (cp.y > 390) {

            [_Logo_01 setHidden:YES];
        }
        if (cp.y < 130) {
            [_Logo_01 setHidden:YES];
        }
        if (cp.x > 290) {
            [_Logo_01 setHidden:YES];
        }
        if (cp.x < 40) {
            [_Logo_01 setHidden:YES];
        }

    }

when i resize my Logo on the app the image resizes correctly but my center point is wrong

I'm sorry i wronged to post code this is the code that i use to scale my images:

- (IBAction)ScaleImage1:(UIPinchGestureRecognizer *)recognizer
{
    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
    recognizer.scale = 1;

    CGFloat height = _Logo_01.frame.size.height;
    NSLog(@"SIZE ===== %f", height);
    if (height > 600) {
        [_Logo_01 setHidden:YES];
    }

}



via Chebli Mohamed

Get current latitude and longitude from didupdatelocation delegate method

I created a MAPVIEW to get latitude and longitude of user's current location.

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

The didUpdateLocations delegate method gives an array which has current location's latitude and longitude.
How do i get latitude and longitude from that array?



via Chebli Mohamed

uipageview controller cannot update dot images using iOS 8?

I have created custom class with subclasss of UIPageControl

customClass.h

@interface customclass : UIPageControl
{
    UIImage* activeImage;
    UIImage* inactiveImage;
}
@property(nonatomic, retain) UIImage* activeImage;
@property(nonatomic, retain) UIImage* inactiveImage;
@property (weak, nonatomic) IBOutlet UIPageControl *pageController;

@end

customclass.m file

@implementation customclass
@synthesize activeImage,inactiveImage;
-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self)
    {
       activeImage = [UIImage imageNamed:@"dots.png"];
       inactiveImage = [UIImage imageNamed:@"off.png"];


    }
    return self;
}
-(id)init
{
    self = [super init];
    if(self)
    {
        activeImage = [UIImage imageNamed:@"dots.png"];
        inactiveImage = [UIImage imageNamed:@"off.png"];

    }
    return self;
}

-(void)updateDots
{
        for (int i = 0; i < [self.subviews count]; i++)
        {
            UIImageView * dot = [self imageViewForSubview:  [self.subviews objectAtIndex: i]];
            if (i == self.currentPage) dot.image = activeImage;
            else dot.image = inactiveImage;
        }

}

- (UIImageView *) imageViewForSubview: (UIView *) view
{
    UIImageView * dot = nil;
    if ([view isKindOfClass: [UIView class]])
    {
        for (UIView* subview in view.subviews)
        {
            if ([subview isKindOfClass:[UIImageView class]])
            {
                dot = (UIImageView *)subview;
                break;
            }
        }
        if (dot == nil)
        {
            dot = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 17,17)];
            [view addSubview:dot];
        }
    }
    else
    {
        dot = (UIImageView *) view;
    }

    return dot;
}


-(void)setCurrentPage:(NSInteger)page
{
    [super setCurrentPage:page];
    [self updateDots];
}

the following line never executed.I am using iOS 8.3

for (int i = 0; i < [self.subviews count]; i++)

here never get into that loop..

i dont know whats going on here..

i am following this Link

i have called at my uipageviewcontroller like this...

pageControl=[[customclass alloc]init];
    [pageControl setCurrentPage:0];



via Chebli Mohamed

type () does not conform to protocol anyobject

I am trying to confirm submission before leaving the view controller :

however I am getting this error :

type () does not conform to protocol anyobject

here is the line where the error appears :

        self.navigationItem.backBarButtonItem?.target = self.validateBeforeBack("back", completion: { (bool) -> () in
        self.navigationController?.popViewControllerAnimated(true)
    })



via Chebli Mohamed

iAd Interstitials not showing consistently? And not at all on the simulator

iAd interstitials aren't showing up at all on the iPhone simulator, and they don't show up consistently on my iPhone. I've gone to the Developer settings, changed the fill rate to 100%, and turned on Unlimited Ad Presentation. No difference... an interstitial will generally show the first time it's supposed to, and then won't show again for anywhere from a few minutes to fifteen minutes. No idea what is causing the difference in time.

Also, there doesn't seem to be a way to track if the interstitial is going to show or not / if it actually showed or didn't. I realize there's an interstitial delegate, but it seems that isn't used anymore. The way I am calling my interstitial is using viewController.interstitialPresentationPolicy = ADInterstitialPresentationPolicy.Automatic

Thanks!



via Chebli Mohamed

Async For Loop in Swift halting execution?

I have a big JSON list of items that I download, which I believe happens asynchronously (good) but when I loop through the JSON to turn them into objects ("Product" objects to be exact), the whole app freezes as the for loop executes.

The offending call

self.dm.getOrderGuideData({ (time: CFAbsoluteTime) in
     self.dm.parseInOrderGuideProducts({ (completion: Bool) in
     })
})

I put them in closures to prevent this but it doesn't seem to be working.

func getOrderGuideData(completion: (time: CFAbsoluteTime) -> ()) {
        let startTime = CFAbsoluteTimeGetCurrent()

        Alamofire.request(.POST, "http://ift.tt/1SHZNzm", parameters: orderGuideRequest, encoding: .JSON) .responseJSON { (req, res, json, error) in

            if error != nil  {
                println("\n\nOG ERROR: \(error!)\n\n")
                println(req)
                println(res)

                let endTime = CFAbsoluteTimeGetCurrent() - startTime
                completion(time: endTime)
            }
            else {

                var jsonForError = JSON(json!)
                if jsonForError["errors"] != nil {
                    println("Order Guide Success")

                    self.rawOrderGuideJSON = json

                    let endTime = CFAbsoluteTimeGetCurrent() - startTime
                    completion(time: endTime)
                }
                else {
                    var error = jsonForError["errors"]
                    println(error)
                    let endTime = CFAbsoluteTimeGetCurrent() - startTime
                    completion(time: endTime)
                }
            }
        }
    }

    func parseInOrderGuideProducts(completion: Bool -> ()) {
        var parsedJSON = JSON(rawOrderGuideJSON!)

        var resultset = parsedJSON["resultset"]
        for (key, subJson) in resultset {
            println(key)

            var newProduct: Product = Product()

            newProduct.title = key as String
//            newProduct.id = parsedJSON["resultset"][key]["materialId"].string
//            newProduct.image = getOrderGuidePhotoForID(newProduct.id!)
            newProduct.id = resultset[key]["materialId"].string
            var price = resultset[key]["price"].double
            newProduct.price = "$\(price!)"
            newProduct.weight = resultset[key]["totalWeight"].string

            orderGuideItemsList.append(newProduct)
        }
        completion(true)
    }

Any ideas on how I can fix this? The output to the console scrolls fine as a the keys are printed (see parseInOrderGuideProducts) but execution on the phone or simulator halts.



via Chebli Mohamed

JS getTimezoneOffset() in iOS

In javascript we can get timezone offset with

var current_date = new Date();
current_date.getTimezoneOffset();

Result => -330

I want to get that in iOS (Objective-C)

can someone help please ?



via Chebli Mohamed

Parse App Crashing On Some Devices

I have an iPhone app which is using parse as backend. I have successfully integrated everything.I've test it and it's running perfectly on my devices ( simulator and physical devices ). The problem is that my clients are complaining that the app is crashing on their devices when trying to fetch data from Parse.

What can be the problem?



via Chebli Mohamed

How do you use Linea Pro Phonegap Plugins

I am working on an Linea Pro app, and have the linea pro plugin found on git hub. I have installed the plugin, and build the app using adobe phonegap build online.

I am using the paid for version, I also have my apple development licence, and my iPod is in development mode.

I have tried downloading examples with use of the plugin in, yet none of the work. and i cant find any more information online to help me.

Any help would be grate.



via Chebli Mohamed

How to get directions between two addresses in iOS

I'm using this code to try get directions between two locations. But it outputs co-ordinates using latitude and longitude. But what I want is to get directions for searching based on 2 addresses. How can I get this code to work with addresses?

MKPlacemark *source = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(37.776142, -122.424774) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil] ];

MKMapItem *srcMapItem = [[MKMapItem alloc]initWithPlacemark:source];
[srcMapItem setName:@""];

MKPlacemark *destination = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(37.73787, -122.373962) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil] ];

MKMapItem *distMapItem = [[MKMapItem alloc]initWithPlacemark:destination];
[distMapItem setName:@""];

MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
[request setSource:srcMapItem];
[request setDestination:distMapItem];
[request setTransportType:MKDirectionsTransportTypeAny];

MKDirections *direction = [[MKDirections alloc]initWithRequest:request];

[direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {

    NSLog(@"response = %@",response);
    NSArray *arrRoutes = [response routes];
    [arrRoutes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        MKRoute *rout = obj;

        MKPolyline *line = [rout polyline];
        [mapview addOverlay:line];
        NSLog(@"Rout Name : %@",rout.name);
        NSLog(@"Total Distance (in Meters) :%f",rout.distance);

        NSArray *steps = [rout steps];

        NSLog(@"Total Steps : %lu",(unsigned long)[steps count]);
        NSMutableArray *stepsArray=[[NSMutableArray alloc] init];
        [steps enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSLog(@"Rout Instruction : %@",[obj instructions]);
            NSLog(@"Rout Distance : %f",[obj distance]);
            [stepsArray addObject:[obj instructions]];
        }];

        [self myShowDirections:response];
        self.steps.text=[NSString stringWithFormat:@"%@",stepsArray];



via Chebli Mohamed

switch tab bar before navigation to another viewcontroller

I am making an iOS app where I have Tab bar + Side Menu.

Tab bar have 5 items and side menu have around 12 menus.

All side menu functionalities are from Tab 1 & side menu is accessible across all views in tab bar.

That means if I am on Tab 2, even I can access side menu. When I click on side menu item from Tab 1, I will go to Tab 1 and then navigation will occur.

What I want to do is let's say if I click on Complains menu from side menu, I want to go to ComplainsViewController.

Code I used is as below.

// go to first tab
self.tabBarController.selectedIndex = 0;
// now navigate
ComplainsViewController *sViewCon = [self.storyboard instantiateViewControllerWithIdentifier:@"Complains"];
CATransition *transition = [CATransition animation];
transition.duration = 0.5;
transition.type = kCATransitionFade;
[self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
[self.navigationController pushViewController:sViewCon animated:NO];

I have two scenario.

Scenario 1 (Correct)

I am on Tab 1 and click on Complains from side menu. When I click, I go successfully to ComplainsViewController using above code.

Scenario 2 (In-Correct)

I am on Tab 2 and click on Complains from side menu. When I click, I go successfully to Tab 1, but I don't navigate to ComplainsViewController. When I click back to Tab 2, I see ComplainsViewController open in Tab 2.

Any idea how to switch first to Tab and then navigate to another viewcontroller?


Edit 1

Below is the basic structure I have.

enter image description here



via Chebli Mohamed

iOS spotlight icon won't show

For my app icon I have crossed Iphone: iOS 8 and later and iOS 7 and later and ipad: iOS 7 and later then I transferred all 12 icons but when I do a spotlight search in my iphone the icon won't show up. Have I missed something?

Also, what does iOS icon is pre-renered option mean and do I need it?

enter image description here

Thanks



via Chebli Mohamed

What is the Swift alternative of radiansToVector and randomInRange Objective-C functions?

I watched an old ios 7 spritekit course and they use these methods. I tried to use them in Swift, but they didn't work. What should I use instead?

static inline CGVector radiansToVector(CGFloat radians) {
    CGVector vector;
    vector.dx = cosf(radians);
    vector.dy = sinf(radians);
    return vector;
}

static inline CGFloat randomInRange(CGFloat low, CGFloat high) {
    CGFloat value = arc4random_uniform(UINT32_MAX) / (CGFloat)UINT32_MAX;
    return value * (high - low) + low;
}



via Chebli Mohamed

iOS keep app always alive, disable scree

I'm building home automation system for my house. The plan is to have lots of different rfduino nodes taking to one wall mounted iPad through the bluetooth.

So far all working perfect apart from keeping an app alive all the time, device is plugged to the charger.

My question is rather simple and I struggle to find a solution. How can I keep the app always alive to do its processing but with the disabled screen?

Thanks in advance



via Chebli Mohamed

Afnetworking 2.0 POST text/plain converts characters

I’m using AfNetworking 2.0 in my iOS project, I have to make a API POST call to my API as text/plain whose body (operation.bodyTextPlain) is a string as this:

MSH|^~\&|DATA||DATA||20150717095405||ORU^R01^ORU_R01|

The problem is before to send the request, the content of the request.HTTPBody is a NSData as this (after convert to NSstring):

MSH%7C%5E\R\%5C%26%7CDATA%7C%7CDATA%7C%

I don’t need AfNetworking replaces the unsafe ASCII characters with “%” followed by two hexadecimal digits, because the response of the request is:

ERR|||207^Determine encoding for message. The following is the first 50 chars of the message for reference, although this may not be where the issue is: 
(null)=MSH%7C%5E\R\%5C%26%7CDATA%7C%7CDATA%7C%7C20^HL70357|E

So, I have the following code:

self.httpClient.requestSerializer = [AFHTTPRequestSerializer serializer];
[self.httpClient.requestSerializer setValue:@"text/plain; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[self.httpClient.requestSerializer setValue:@"text/plain" forHTTPHeaderField:@"Accept"];

[self.httpClient POST:operation.url parameters:operation.bodyTextPlain success:^(NSURLSessionDataTask *task, id responseObject) {

    if ([self isOKResponse:responseObject]) {
        [self operationResult:self.myObject error:nil];
    } else {
        [self operationResult:nil error:self.e];
    }

} failure:^(NSURLSessionDataTask *task, NSError *error) {
    [self operationResult:nil error:error];
}];
self.httpClient.requestSerializer = [AFJSONRequestSerializer serializer];

Really grateful for your help.



via Chebli Mohamed

Open iCloud drive programatically

I'm using CloudKit in my app and I want to send the user to iCloud settings in case he/she hasn't enabled or set it up. I am currently using the following code:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];

But it opens the following:

enter image description here

So the user would have to go back and look for iCloud to set it up, how can I redirect the user directly to iCloud settings?

Thanks in advance!



via Chebli Mohamed

How to create two radio buttons on one uitableview cell

I have created two radio buttons on one tableview cell.That are options for a question,But when I select them they both are get selected that I don't want,I want to select only one of them but I am not able to do that......Please help me Here is my code for customCell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    customCell *cell = (customCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"customCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];

    }

    leftBtnclick = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtnclick setTag:0];
    [leftBtnclick setImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];
    [leftBtnclick setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected];
    [leftBtnclick setFrame:CGRectMake(50, 120, 30, 30)];
    [leftBtnclick addTarget:self action:@selector(leftTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:leftBtnclick];

    rightBtnclick = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtnclick setTag:1];
    [rightBtnclick setImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];
    [rightBtnclick setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected];
    [rightBtnclick setFrame:CGRectMake(180, 120, 30, 30)];
    [rightBtnclick addTarget:self action:@selector(rightTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:rightBtnclick];


    cell.numberLbl.text = [numberArray objectAtIndex:indexPath.row];
    return cell;
}


-(void)leftTickBtnClicked:(id)sender
{
    if ([leftBtnclick isSelected]) {
        [sender setImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];

    else
    {
      [sender setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];

    }



}

-(void)rightTickBtnClicked:(id)sender
{
    if ([sender isSelected])
    {
         [sender setImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];
    }
    else
    {
        [sender setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
    }



}



via Chebli Mohamed

Why label shows previous value and current values in uitableview?

enter image description here

my code:

     -(void)btn_up_arrow:(UIButton*)click
{

    int tagvalue=[[arr_count objectAtIndex:click.tag] intValue];

    tagvalue++;
    [arr_count replaceObjectAtIndex:click.tag withObject:[NSString stringWithFormat:@"%d",tagvalue]];
       NSLog(@"increment %@",arr_count);
if(tagvalue >=5)

{


    tagvalue--;
    [arr_count replaceObjectAtIndex:click.tag withObject:[NSString stringWithFormat:@"%d",tagvalue]];
}
    label1.text=[NSString stringWithFormat:@"%d",tagvalue];

    [self.mTableView reloadInputViews];

}

i cant reload the cell in the out of tableview method. tqtableview i am used, please help me to find this problem.



via Chebli Mohamed

How do you test certificate pinning with Alamofire?

So I followed Alamofire's instructions on the Read Me regarding their new Server Trust Policy. Got the certificate from the server, added it to my project and implemented the following code in my project:

let serverTrustPolicies: [String: ServerTrustPolicy] = [
        "someserver.withvalidcer.com": .PinCertificates(
            certificates: ServerTrustPolicy.certificatesInBundle(),
            validateCertificateChain: true,
            validateHost: true
        )
    ]

    let manager = Manager(
        configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
        serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
    )

My question is how do I test this?

I've tried changing my base api url to our test server, which has a different valid certificate, but the api calls are not being rejected. And I have verified that the code is running on the required api calls.



via Chebli Mohamed

Wordpress on iPad, logo position issue

I'm developing this site: esident.logotypefactory.com Everything is ok on desktops, phones. But when it comes to iPads the logo duplicates or something is wrong...

So try this:

1) Go to esident.logotypefactory.com on your iPad 2) Swipe to the left so the screen goes to the right, you will see the second logotype.

Why does it do like that? What am I doing wrong?

What I want:

1) Have a logo always on the top left side. 2) When you click on the menu, have the logo also there on same place.

What I think:

That the second logo is the logo that should be viewable when you click on the menu. As when you click on the menu, you can't "swipe" to see the second logo.

Please help me guys.

<div class="fusion-header"><div class="fusion-row"><div class="fusion-logo" data-margin-top="65px" data-margin-bottom="31px" data-margin-left="0px" data-margin-right="0px"> <a href="http://ift.tt/1M988Ig"> <img src="http://ift.tt/1ImH3v2" width="221" height="51" alt="Esident" class="fusion-logo-1x fusion-standard-logo"> <img src="http://ift.tt/1ImH3v2" width="221" height="51" alt="Esident" style="width:221px; max-height: 51px; height: auto;" class="fusion-standard-logo fusion-logo-2x"> <img src="http://ift.tt/1M988Ii" alt="Esident" class="fusion-logo-1x fusion-mobile-logo-1x"> <img src="http://ift.tt/1ImH3v2" alt="Esident" style="max-width:195px; max-height: 47px; height: auto;" class="fusion-logo-2x fusion-mobile-logo-2x"> </a></div><div class="fusion-mobile-menu-icons"><a href="#" class="fusion-icon fusion-icon-bars"></a></div><div class="fusion-mobile-nav-holder"></div></div></div>



via Chebli Mohamed

Using cellular data crashes application when using NSUrl + NSData

I have an application made in Swift that uses NSUrl and NSData to get a JSON response from an API.

If I am on cellular data, the app closes as soon as it tries to make the connection. On WiFi (or the emulator) it is fine.

I found this article which seems to show there might be a bug, but its not based in Swift and it's not using the same components.

How can I set the "setAllowCellularAccess" option in my application?

My code:

let loginUrl = "<my server URL>"
var message  :String
var success : Int
var endPoint = NSUrl(string: loginUrl + username + "/" + password)
var data = NSData(contentsOfUrl: endPoint!)



via Chebli Mohamed

How to make a click on cell of a Table View in Swift

This is my first day in the awesome SWIFT language, I'm trying to populate a Table view with some data, everything seems to work fine, but I want to make my Table view clickable and print the id of the item clicked but it doesn't seem to be working I'm not getting any Error.

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var categories = [Category]()

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return categories.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
    cell.textLabel?.text = categories[indexPath.row].Label



    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
 println("You selected cell #\(indexPath.row)!")
}



override func viewDidLoad() {
    super.viewDidLoad()


    let reposURL = NSURL(string: "http://ift.tt/1z9CvXr")
    // 2
    if let JSONData = NSData(contentsOfURL: reposURL!) {
        // 3
        if let json = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: nil) as? NSDictionary {
            // 4
            if let reposArray = json["List"] as? [NSDictionary] {
                // 5
                for item in reposArray {
                    categories.append(Category(json: item))
                }
            }
        }
    }
}

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


}



via Chebli Mohamed

Appling impulse on a SpriteKit node

I'm developing a SpriteKit Game,In which i have a node named hero who dodges the villains approaching,I have an issue in appyImpulse for a jump action and in this case user's can jump repeatedly and fly instead of dodging them,I used boolean variable to change the status with a timer value to jump only once in 3 seconds that is not working,And Im new to SpriteKit here is my code

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    if isGameOver == true {
        self.restart()
    }

    if isstarted {
        self.runAction(SKAction.playSoundFileNamed("jump.wav", waitForCompletion: false))
        for touch: AnyObject in touches{
            if jumpon == false {  //hero has not jumped
                    let location = touch.locationInNode(self)
                    heroAction()
                    jumpon = true   //hero jumped
            }
        }

    } else { 
        isstarted = true
        hero.stop()
        hero.armMove()
        hero.rightLegMove()
        hero.leftLegMove()
        treeMove()
        villanMove()
        let clickToStartLable = childNodeWithName("clickTostartLable")
        clickToStartLable?.removeFromParent()
        addGrass()
       // star.generateStarWithSpawnTime()
    }

}

func changeJump(){
    jumpon = false // hero has landed
}

and function update is called in every second and then changeJump must be called

 override func update(currentTime: CFTimeInterval) {

    if isstarted == true {
        let pointsLabel = childNodeWithName("pointsLabel") as MLpoints
        pointsLabel.increment()
    }

    if jumpon == true { // checked everyframe that hero jumped
        jumpingTimer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "changeJump", userInfo: nil, repeats: true) // changing jump status
    }
}

how should i update my code to make the villain jump only once in three seconds,thanks in advance



via Chebli Mohamed

while compiling "unknown type name error" occur

I am having some trouble in compiling code on X-code 6.0 A class(one) i imported to ViewController class. when i made object of class(one)

it gives "unknown type name error".

please help me with this.



via Chebli Mohamed