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

dimanche 28 juin 2015

how to run simple ODATA query dynamically and return result in json format using with Roslyn?

I'm working on query builder for simple Odata

I'm generating simple odata queries dynamically and want to show result of queries on json format.

query text:

   var DetailData = await myClient.For<CustomerDetail>().Filter(q => q.Id == id).OrderBy(q => q.Key).FindEntriesAsync();

how to run simple ODATA query dynamically and return result in json format?

Swift Haneke: Json Data in TextView

I used the Haneke Framework to get Data from a Site. With the Haneke Framework i also can get Images from a site, and these Images i can present on a UIImageView. Now i wanted to get some text from a site.

I did it like this:

 cache.fetch(URL: URL).onSuccess { JSON in
            println(JSON.dictionary?["index"])

It printed me all the data from "Index".

Now i want, that all the data from "Index" should be presented on a UITextView.

  self.textView.text = JSON.dictionary["index"]

But it doesn't work..

I get the error: Cannot assign a value of type 'AnyObject' to a value of type 'String!'

I have to unwrap it or?

How do I access the element title in the Json?

I want GET json from http://omadbapi.com/?s= for search script, but I'm having trouble with get Title elment in this JSON :

{
"Search": [
{
  "Title": "Sherlock Holmes: A Game of Shadows",
  "Year": "2011",
  "imdbID": "tt1515091",
  "Type": "movie"
},
{
  "Title": "Spy Kids 3-D: Game Over",
  "Year": "2003",
  "imdbID": "tt0338459",
  "Type": "movie"
}
]
}

JavaScript :

$(document).ready(function () {
    var url = 'http://www.omdbapi.com/?',
        mode = 's=',
        input,
        movieName;

    $('button').click(function() {
        var input = $('#movie').val(),
        movieName = encodeURI(input);

        $.getJSON( url + mode + input, function( data ) {

          $.each(data, function(e,p) {
            document.getElementById("item").innerHTML="Title : " + p.Title;
          });
    });
    });
});

p.Title or data.Title, I don't know...

"No matching records found" NOT displayed in "bootstrap-table"

I am using the "bootstrap-table" plugin for my website and currently using it's server side pagination properties.

The table is being populated correctly and the search feature also works. BUT when something not present is searched for it displays all the records instead of displaying "No matching records found".

This is the html code I am using...

<table data-toggle="table"
       data-url="1.php"
       data-pagination="true"
       data-side-pagination="server"
       data-page-list="[5, 10, 20, 50, 100, 200]"
       data-search="true"
       data-height="300">
    <thead>
    <tr>
        <th data-field="state" data-checkbox="true"></th>
        <th data-field="memberID" data-align="right" data-sortable="true">Member ID</th>
        <th data-field="name" data-align="center" data-sortable="true"> Name</th>
        <th data-field="dob" data-sortable="true">Date of Birth</th>
    </tr>
    </thead>


</table>

and this is the php script I am using to create the JSON response...

<?php

require_once('db-connect.php');

if(isset($_GET["limit"])) {
    $limit = $_GET["limit"];
} else {
    $limit = 10;
}

if(isset($_GET["offset"])) {
    $offset = $_GET["offset"];
} else {
    $offset = 0;
}

if(isset($_GET["sort"])) {
    $sort = $_GET["sort"];
} else {
    $sort = "";
}

if(isset($_GET["order"])) {
    $order = $_GET["order"];
} else {
    $order = "asc";
}

 if(isset($_GET["search"])) {
    $search = $_GET["search"];
 } else {
    $search = "";
 }


if($search == "") {
    $result = mysqli_query($connection,"select memberID, name, dob from memberdetails" );
} else {

    $result = mysqli_query($connection,"select memberID, name, dob from memberdetails WHERE memberID LIKE '%$search%'"  );
}


$row = array();

if ( mysqli_num_rows($result) > 0 ) {
            while($row = mysqli_fetch_assoc($result)) {
                $result_2d_arr[] = array (  'memberID' => $row['memberID'],
                                            'name' => $row['name'],
                                            'dob' => $row['dob']);
            }




//get the result size
$count = sizeof($result_2d_arr);

//order the array
if($order != "asc") {
    $result_2d_arr = array_reverse($result_2d_arr);
}

//get the subview of the array
$result_2d_arr = array_slice($result_2d_arr, $offset, $limit);



echo "{";
echo '"total": ' . $count . ',';
echo '"rows": ';
echo json_encode($result_2d_arr);
echo "}";

}

?>

The JSON response is as follows...

{"total": 23,"rows": [{"memberID":"1","name":"asd","dob":"2015-06-03"},{"memberID":"2","name":"asd","dob":"2015-06-03"},{"memberID":"3","name":"asd","dob":"2015-06-03"},{"memberID":"4","name":"asd","dob":"2015-06-03"},{"memberID":"5","name":"asd","dob":"2015-06-03"},{"memberID":"6","name":"asd","dob":"2015-06-03"},{"memberID":"7","name":"asd","dob":"2015-06-03"},{"memberID":"8","name":"asd","dob":"2015-06-03"},{"memberID":"9","name":"asd","dob":"2015-06-03"},{"memberID":"10","name":"asd","dob":"2015-06-03"}]}

Handle Post Data of JSON in PHP

I receive JSON post data ....

{"split_info":"17076370","customerName":"Lahoti","status":"failed","error_Message":"fail.","paymentId":"17076370","productInfo":"productInfo","customerEmail":"cxxxx.xx@gmail.com","customerPhone":"999999999","merchantTransactionId":"BR121","amount":"19.0","notificationId":"443"}

I have written PHP code to Update my Database using merchantTransactionId received as JSON post data. My database is not going to update... My php code is as below Please help..

<?php
include("dbconnection.php");
if(isset($_POST))
{
$json_a = json_decode($_POST, true);
 $Id=$json_a['merchantTransactionId'];
 $status="payUMoney";
 mysql_query("UPDATE std status= '".$payStatus."' WHERE Id='".$Id."'",$db);
?>

POST raw json code ios

i'm new to ios developing and i want to ask how can i post a raw json code to the server.

For Example: i want to send this JSON raw data to http://example.com/user

{ "user": 
                {   "username": "jkaaannyaad11",
                    "password": "secret123456",
                    "gender": "male",
                    "first_name": "assd",
                    "last_name": "ffsasd",
                    "birth_date": "can be null",
                    "phone_number": "12343234",
                                                                  "have_car":"1",
                                                                  "same_gender" :"0",
                                                                  "uid": "this is id for facebook , can be null"
                },
            "home": {
                    "longitude": "31.380301",
                    "latitude": "30.054272",
                    "name": "city"
                    },
            "work": {
                    "longitude": "30.068237",
                    "latitude": "31.024275",
                    "name": "village"
                    },
            "email": {
                    "email_type": "work",
                    "email": "hello.me@me.com"
                    }
            }

so how can i do it ?

Dearest Regards,

How can i parse json array?

I am building an Android app and i need to populate a custom listview with some data from my localhost. I am trying to use volley JsonArrayRequest to get that data under the format of a JSONObject array but all i get is org.json.JSONException: End of input at character 0 of. This is my json array request :

final String URL = "http://ift.tt/1TXdybA";
        JsonArrayRequest productsReq = new JsonArrayRequest(Method.POST, URL, new Listener<JSONArray>() {

            @Override
            public void onResponse(JSONArray response) {
                Log.d("productTAG", response.toString());
                for(int i = 0; i < response.length(); i++)
                {
                    try 
                    {   
                        JSONObject productObj = response.getJSONObject(i);
                        String title = productObj.getString("title");
                        String description = productObj.getString("description");
                        String category = productObj.getString("category");
                        String subCategory = productObj.getString("subCategory");
                        String size = productObj.getString("size");
                        String price = productObj.getString("price");
                        String thumbnailUrl = productObj.getString("image_one");

                        Product product = new Product(title, thumbnailUrl, description, category, subCategory, size, price);
                        products.add(product);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }
        }, new ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("products_error", error.getMessage().toString());
                error.printStackTrace();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();

                params.put("req", "products");
                params.put("category", category);
                params.put("subCategory", subCategory);

                return params;
            }
        };
        VolleyCore.getInstance(getActivity()).addToRequestQueue(productsReq); 

The method i am using is POST and under the getParams i am adding a tag named req which has the value products. I am checking for this tag in index.php. This is my function that queries the table:

public function getItems($category, $subCategory)
    {
        $query = mysql_query("SELECT * FROM items WHERE category = '$category' AND sub_category = '$subCategory'") or die(mysql_error());


        $objects = array();
        if($query)
        {
            while($objects = mysql_fetch_assoc($query))
            {
                $final[] = $objects;
            }
        }
        return $final;

    }

Here in index.php i am checking for the request:

if(isset($_POST['req']) && $_POST['req'] == 'products')
    {
        $category = $_POST['category'];
        $subCategory = $_POST['subCategory'];


        $obj = $func->getItems($category, $subCategory);

        echo json_encode($obj);

    }

$func is the instantiation of the class where i keep all the methods working with the database(including getItems()). If i use volley StringRequest i do get a response back, but then again why don't i get the response while using JsonArrayRequest ? What am i doing wrong?

Parsing json with gson and java

I am struggling to parse a json output with Java and gson, but I am really stuck.

I would appreciate any suugestion.

This is my sample JSON file:

{
"sportId": 29,
"last": 26142386,
"league": [
    {
        "id": 1833,
        "events": [
            {
                "id": 383911973,
                "starts": "2015-01-22T21:00:00Z",
                "home": "America de Natal",
                "away": "Barras",
                "rotNum": "901",
                "liveStatus": 0,
                "status": "O",
                "parlayRestriction": 0
            },
            {
                "id": 383911974,
                "starts": "2015-01-22T21:00:00Z",
                "home": "Baraunas RN",
                "away": "ASSU RN",
                "rotNum": "904",
                "liveStatus": 0,
                "status": "O",
                "parlayRestriction": 0
            }
        ]
    }
  ]
}

My target is to a make a 2-dimensional array (or something similar) of the form:

leagueId, eventId, home, away
------------------------------
   1         1       a    b
   .         .       .    .
   .         .       .    .
  etc       etc     etc   etc

in order to insert the data in a MYSQL table.

I have write the following classes:

public class Fixtures {
int last;
int sportId;
ArrayList<Leagues> league = new ArrayList<Leagues>();

public ArrayList<Leagues> getListOfLeagues() {  
    return league;  
}  

public int getSportId(){
    return sportId;
}

 public int getLast(){
    return last;
 }

}

public class Leagues {
int id;
ArrayList<Events> events;

public int getLeagueId(){
    return id;
}

 public ArrayList<Events> getListOfEvents() {  
    return events;  
 }  

}

public class Events {
int id;
String home;
String away;


public int getEventId(){
    return id;
}

public String getHome() {  
    return home;  
}  

 public String getAway() {
    return away;
 }


}

and

Gson gson = new GsonBuilder().create();             
Fixtures fixture = gson.fromJson(jsonsource, Fixtures.class);
System.out.println(fixture.getSportId());
System.out.println(fixture.getLast());

ArrayList<Leagues> Leagues = fixture.getListOfLeagues();

Dont know how to proceed :(

Mapping a large json object (from rest service) to a smaller object? LoDash?

I am receiving a list of tweets (from a rest service) which is a really big list of many properties but I am only interested in a few properties in each item in the collection that is returned.

What is the best way of mapping this to a smaller object?

Does lodash help here?

I do I just iterate over it and create many new object?

Any help appreciated.

How to store data of dynamically generated Forms on Submit in Android?

I am developing a android application in which I am creating different dynamic form controls of different forms from the JSON data at runtime. The form may contain EditText, Spinner, Chechboxlist, Radiobuttonlist or five Addressboxes of EditText. Each control may also appear multiple times in different order. Now, I have generated and displayed the form controls of different forms at runtime.

One Example Form :

TextBox1 : ___________

Spinner2 : Item1 Item2 Item3

TextBox3 : ___________

Checkbox4 :

  • Option1
  • Option2
  • Option3

Radiogroup5 :

  • Radio1
  • Radio2

Spinner6 : Item1 Item2

Checkbox7 :

  • Option1
  • Option2

Radiogroup8 :

  • Radio1
  • Radio2

Address9 : _____________ _____________ _____________ _____________ _____________

Here Address contains five EditText consecutively.Now other form may or may not contain this controls.Here TextBox1, Spinner2, TextBox3 etc are the unique label to identify the control. But my problem is to submit the data entered in the form. The form contains a submit button. By pressing it, I have to send POST JSON Request by form the JSON with the filled data.

Example JSON Request :

  { "FormData" : {
              {"Name":"TextBox1" , "Value":"DummyText"},
              {"Name":"Spinner2" , "Value":"Item3"},
              {"Name":"TextBox3" , "Value":"DummyText"},
              {"Name":"Checkbox4" , "Value":"Option2, Option3"},
              {"Name":"Radiogroup5" , "Value":"Radio2"},
              {"Name":"Spinner6" , "Value":"Item1"},
              {"Name":"Checkbox7" , "Value":"Option1"},
              {"Name":"Radiogroup8" , "Value":"Radio1"},
              {"Name":"Address9" , "Value":"Dummy1, Dummy2, Dummy3, Dummy4,Dummy5"} 



           }

So how to write the proper single code for storing and submitting that data for a particular dynamic form in a data structure in such a way that I can form that JSON Request? Thanks in advance.

Laravel 5 how to return a template with response()->json()?

Below is my database:

post:
id user_name content created_at

Below is my post controller:

public function new(Request $request){
        $data = $request->all();
        $post = new Post;
        $post->user_name = $data['name'];
        $post->message = $data['content'];
        $post->save();
        $id = $post->id;
        $show = Post::find($id)->first();
        // $html = view('wall.post')->with('post', $show);
        return response()->json(['success' => $post->id,'message'=> 'Post Sent', 'html' => $html]);
    }

and my /views/wall/post.blade.php :

<div class="ui post">
<div class="name">User : {{ $post->user_name }}</div>
<div class="content">{{ $post->content }}</div>
</div>

Below is my question:

how do i get the content from post.blade.php with user_name and content return as below to $html in new() when i post name=kenny and content=testing:

<div class="ui post">
<div class="name">User : Kenny</div>
<div class="content">Testing</div>
</div>

and i just use jquery to prepend above code to my page?

Thanks

{Sorry if i got bad grammar in my english}

Select an arrray from JSON data on PHP

everyone!

I'm working on a movie website(which obviously not completed). I want to know how to export data from an API and select an array from JSON data on PHP. In this case, I want to output the title of the movie but it seems to not working. I get this error: Notice: Trying to get property of non-object. From the error, I know that I'm trying to output an object, not a string but I don't know how to resolve it.

Here's my index.php file:

<?php
require_once('includes/variables.php');
 ?>
 <!DOCTYPE html>
 <html>
    <body>
    <?php
        echo $movieNameList->data->movies[1]->id;
    ?>
</body>
</html>

includes/variables.php file:

 <?php
 $getMovieList = file_get_contents('http://ift.tt/1xsOjG3');
 $movieNameList = json_decode($getMovieList[0]);
 ?>

http://ift.tt/1xsOjG3 file if you're lazy:

{  
   "status":"ok",
   "status_message":"Query was successful",
   "data":{  
      "movie_count":4220,
      "limit":2,
      "page_number":1,
      "movies":[  
         {  
            "id":4247,
            "url":"https:\/\/yts.to\/movie\/rem-by-mtv-2014",
            "imdb_code":"tt4066748",
            "title":"R.E.M. by MTV",
            "title_long":"R.E.M. by MTV (2014)",
            "slug":"rem-by-mtv-2014",
            "year":2014,
            "rating":8,
            "runtime":107,
            "genres":[  
               "Documentary"
            ],
            "language":"English",
            "mpa_rating":"Unknown",
            "background_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/rem_by_mtv_2014\/background.jpg",
            "small_cover_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/rem_by_mtv_2014\/small-cover.jpg",
            "medium_cover_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/rem_by_mtv_2014\/medium-cover.jpg",
            "state":"ok",
            "torrents":[  
               {  
                  "url":"https:\/\/yts.to\/torrent\/download\/1F28D13F40AE91AECC58D649F5F9D84D29321632.torrent",
                  "hash":"1F28D13F40AE91AECC58D649F5F9D84D29321632",
                  "quality":"720p",
                  "seeds":1063,
                  "peers":544,
                  "size":"812.23 MB",
                  "size_bytes":851680192,
                  "date_uploaded":"2015-06-28 08:49:09",
                  "date_uploaded_unix":1435438149
               },
               {  
                  "url":"https:\/\/yts.to\/torrent\/download\/DED26397FD36DFC932BB5EEEC82D25204699943C.torrent",
                  "hash":"DED26397FD36DFC932BB5EEEC82D25204699943C",
                  "quality":"1080p",
                  "seeds":247,
                  "peers":419,
                  "size":"1.65 GB",
                  "size_bytes":1766838835,
                  "date_uploaded":"2015-06-28 22:55:41",
                  "date_uploaded_unix":1435488941
               }
            ],
            "date_uploaded":"2015-06-28 08:49:06",
            "date_uploaded_unix":1435438146
         },
         {  
            "id":4245,
            "url":"https:\/\/yts.to\/movie\/bigfoot-county-2012",
            "imdb_code":"tt2108605",
            "title":"Bigfoot County",
            "title_long":"Bigfoot County (2012)",
            "slug":"bigfoot-county-2012",
            "year":2012,
            "rating":2.9,
            "runtime":82,
            "genres":[  
               "Horror",
               "Mystery"
            ],
            "language":"English",
            "mpa_rating":"R",
            "background_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/bigfoot_county_2012\/background.jpg",
            "small_cover_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/bigfoot_county_2012\/small-cover.jpg",
            "medium_cover_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/bigfoot_county_2012\/medium-cover.jpg",
            "state":"ok",
            "torrents":[  
               {  
                  "url":"https:\/\/yts.to\/torrent\/download\/25E5FBDAD49BFD067EEB7778EF1CED753E0E608C.torrent",
                  "hash":"25E5FBDAD49BFD067EEB7778EF1CED753E0E608C",
                  "quality":"720p",
                  "seeds":324,
                  "peers":183,
                  "size":"693.01 MB",
                  "size_bytes":726671831,
                  "date_uploaded":"2015-06-27 14:02:07",
                  "date_uploaded_unix":1435370527
               }
            ],
            "date_uploaded":"2015-06-27 14:02:06",
            "date_uploaded_unix":1435370526
         }
      ]
   },
   "@meta":{  
      "server_time":1435498431,
      "server_timezone":"Pacific\/Auckland",
      "api_version":2,
      "execution_time":"12.3 ms"
   }
}

Can not get one item out of Json

tryign to pull the items from this json, it dosent work, any suggestions?

   <pre>{{statistics|json}}</pre>

<div class = "list">
        <a class =" item" 
           ng-repeat="item in statistics ">




         <p class="title"> {{item.token}} </p>  


        </a>
</div>

how to parse json using GSON in android?

can any body parse this json for me using GSON i tried many time but, failed.

{
    "posting_detail": {
        "posting_id": "14",
        "posting_title": "LuLu Last Offer",
        "posting_desc": "dqwewqewe",
        "mobile_number": "2344234234",
        "phone_number": "34234324",
        "address": "fefdsfds",
        "city_name": "Abu Dhabi",
        "created_on": "2015-06-22 14:55:05",
        "normal_price": null,
        "images": [
            {
                "photo_img": "http://xyz/images/posting/IMG_1212121219.jpg"
            },
            {
                "photo_img": "http://xyz/images/posting/IMG_1212121220.jpg"
            }
        ]
    }
}

Thanks in advance

Passing parameter to partial view - Rails 4/postgresql/json

I have a Deal model with a column/attribute called 'deal_info' which is a json column.

It looks like this for example

deal1.deal_info = [ { "modal_id": "4", "text1":"lorem" }, 
          { "modal_id": "6", "video2":"yonak" },
          { "modal_id": "9", "video2":"boom" } ] 
deal2.deal_info = [ { "modal_id": "10", "text1":"lorem" }, 
          { "modal_id": "11", "video2":"yonak" },
          { "modal_id": "11", "image4":"boom" } ]

On my view deal.html.erb, i have:

<%= for deal_nb in 0..@deal.number_of_deals do %>
  <div class="modal fade" id="myInfoModal<%= modal_nb %>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <!-- render the right modal type -->
    <%= render "layouts/modal_type_partials/mt#{ @deal.deal_info[deal_nb]['modal_id'] }", parameter_i_want_to_pass: deal_nb  %>
  </div>
<% end %>

Above, as you see above, I'd like to pass for each iteration of the loop inside parameter_i_want_to_pass the number of the iteration loop (2nd iteration would be parameter_i_want_to_pass= 2 for example).

On the partial I have:

<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <h4 class="modal-title" id="myModalLabel">this is mt4</h4>
    </div>
    <div class="modal-body">
      this is the text: <%= @deal.deal_info[parameter_i_want_to_pass]['text1'] %> 

    </div>
  </div>

I get the following error:

no implicit conversion of String into Integer (on line "this is the text: <%= @deal.deal_info[parameter_i_want_to_pass]")

Actually I even tried to detect more easily the bug by just passing a set number instead of the variable 'deal_nb'

<%= render "layouts/modal_type_partials/mt#{ @deal.deal_info[deal_nb]['modal_id'] }", parameter_i_want_to_pass: 2  %>

But I still get exactly the same error.

Best way to display JSON (well formatted) in UITextView or UIWebView in iOS

I need to display SJON in my iPhone app. Currently I am getting unformatted JSON - like one big string with no indentation.

What would be the best way to display this?

Thanks,

Safe Dynamic JSON Casts In Swift

I suspect that I am not quite grokking Swift 1.2, and I need to RTFM a bit more.

I'm working on a Swift app that reads JSON data from a URI.

If the JSON data is bad, or nonexistent, no issue. The JSON object never instantiates.

However, if the JSON data is good JSON, but not what I want, the object instantiates, but contains a structure that is not what I'm looking for, I get a runtime error.

I looked at using Swift's "RTTI" (dynamicType), but that always returns "<Swift.AnyObject>", no matter what the data is.

I want the JSON to be a specific format: An array of Dictionaries:

[[String:String]]! JSON: [{"key":"value"},{"key","value"},{"Key":"value"}]

If I feed it a single element:

{"Key":"value"}

The routine I have tries to cast it, and that fails.

I want to test the JSON object to make sure that it has a structure I want before casting.

    if(nil != inData) {
        let rawJSONObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(inData, options: nil, error: nil)
        println("Type:\(rawJSONObject.dynamicType)")
        if(nil != rawJSONObject) {
            // THE LINE BELOW BLOWS UP IF I FEED IT "BAD/GOOD" JSON:
            let jsonObject: [[String:String]]! = rawJSONObject as! [[String:String]]!
            // I NEED TO TEST IT BEFORE DOING THE CAST
            if((nil != jsonObject) && (0 < jsonObject.count)) {
                let jsonDictionary: [String:String] = jsonObject[0]
                if("1" == jsonDictionary["semanticAdmin"]) { // We have to have the semantic admin flag set.
                    let testString: String!  = jsonDictionary["versionInt"]

                    if(nil != testString) {
                        let version = testString.toInt()

                        if(version >= self.s_minServerVersion) {    // Has to be a valid version for us to pay attention.
                            self.serverVersionAsInt = version!
                        }
                    }
                }
            }
        }
    }

My question is, is there a good way to test an NSJSONSerialization response for the structure of the JSON before uwinding/casting it?

I feel as if this question may be closer to what I need, but I am having trouble "casting" it to my current issue.

JSON Parsing in Ruby

I'm trying to parse the below from JSON (using the JSON gem) in Ruby:

"daily":{"summary":"Light rain today through Saturday, with temperatures rising to 88°F on Saturday.","icon":"rain","data":[{"time":1435464000,"precipProbability":0.99}]}

Currently what I have is this: forecast["daily"]["data"], but I want to get the precipProbability for time "1435464000". Any suggestion on how to complete my current JSON parsing "query"?

How do I write a json file in a specific format?

I'm nearly done with my program, it loads perfect but one issue I'm having is when I edit the json file through my program, I cannot reload the json file because when I save the file, the formatting becomes different.

So my question is how do I format the json file the same as I'm reading it?

Here's my method for writting a new json file.

    public static boolean write(File npcDefFile) {
    try {
        FileWriter writer = new FileWriter(npcDefFile);
        Throwable localThrowable3 = null;
        try {
            Gson gson = new Gson();
            String json = gson.toJson(NPCDefinitions.getNPCDefinitions());
            writer.write(json);
            writer.flush();
        } catch (Throwable localThrowable1) {
            localThrowable3 = localThrowable1;
            throw localThrowable1;
        } finally {
            if (writer != null) {
                if (localThrowable3 != null) {
                    try {
                        writer.close();
                    } catch (Throwable localThrowable2) {
                        localThrowable3.addSuppressed(localThrowable2);
                    }
                } else {
                    writer.close();
                }
            }
        }
    } catch (NullPointerException | IOException e) {
        System.out.println(e.getLocalizedMessage());
        return false;
    }
    return true;
}

Here's the correct format (3 Space Tab)

    [
  {
    "id": 0,
    "name": "Hans",
    "examine": "Servant of the Duke of Lumbridge.",
    "combat": 0,
    "size": 1,
    "attackable": false,
    "aggressive": false,
    "retreats": false,
    "poisonous": false,
    "respawn": 10,
    "maxHit": 0,
    "hitpoints": 0,
    "attackSpeed": 7,
    "attackAnim": 0,
    "defenceAnim": 0,
    "deathAnim": 0,
    "attackBonus": 0,
    "defenceMelee": 0,
    "defenceRange": 0,
    "defenceMage": 0
  },
  {
    "id": 1,
    "name": "Man",
    "examine": "One of Wildy's many citizens.",
    "combat": 2,
    "size": 1,
    "attackable": true,
    "aggressive": false,
    "retreats": true,
    "poisonous": false,
    "respawn": 10,
    "maxHit": 1,
    "hitpoints": 7,
    "attackSpeed": 7,
    "attackAnim": 422,
    "defenceAnim": 1834,
    "deathAnim": 836,
    "attackBonus": 9,
    "defenceMelee": 9,
    "defenceRange": 9,
    "defenceMage": 0
  }
]

Here's the format after I save the file to a new json file. (Compact)

[{"id":0,"name":"Hans","examine":"Servant of the Duke of               Lumbridge.","combat":0,"size":1,"attackable":false,"aggressive":false,"retreats":false,"poisonous":false,"respawn":10,"maxhit":0,"hp":0,"attackspeed":7,"attackanim":0,"defenceanim":0,"deathanim":0,"attackbonus":0,"defencemelee":0,"defencerange":0,"defencemage":0},{"id":1,"name":"Man","examine":"One of Wildy\u0027s many citizens.","combat":2,"size":1,"attackable":true,"aggressive":false,"retreats":true,"poisonous":false,"respawn":10,"maxhit":1,"hp":7,"attackspeed":7,"attackanim":422,"defenceanim":1834,"deathanim":836,"attackbonus":9,"defencemelee":9,"defencerange":9,"defencemage":0}]

This is how I'm loading the json file.

    /**
 * A dynamic method that allows the user to read and modify the parsed data.
 *
 * @param reader
 *            the reader for retrieving the parsed data.
 * @param builder
 *            the builder for retrieving the parsed data.
 */
public abstract void load(JsonObject reader, Gson builder);

/**
 * Loads the parsed data. How the data is loaded is defined by
 * {@link JsonLoader#load(JsonObject, Gson)}.
 *
 * @return the loader instance, for chaining.
 */
public final JsonLoader load() {
    try (FileReader in = new FileReader(Paths.get(path).toFile())) {
        JsonParser parser = new JsonParser();
        JsonArray array = (JsonArray) parser.parse(in);
        Gson builder = new GsonBuilder().create();

        for (int i = 0; i < array.size(); i++) {
            JsonObject reader = (JsonObject) array.get(i);
            load(reader, builder);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return this;
}

Any help would be appreciated.

EDIT:

Here's an exception that was caught.

java.lang.NullPointerException
at NpcDefinitionLoader.load(NpcDefinitionLoader.java:28)
at JsonLoader.load(JsonLoader.java:56)
at NPCDefinitions.loadNPCDefinitions(NPCDefinitions.java:76)
at DefinitionEditor.loadFile(DefinitionEditor.java:171)
at DefinitionEditor.loadButtonActionPerformed(DefinitionEditor.java:790)
at DefinitionEditor.actionPerformed(DefinitionEditor.java:827)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased

Here's the first line the error occured.

int maxHit = reader.get("maxHit").getAsInt();

Second line error

load(reader, builder);