dimanche 28 juin 2015

Cocoa Windows, not receiving events

For the last few days I've returned to an issue that I've been having for a while now. I've been trying to integrate Cocoa windows into my application, but the [NSApplication run] doesn't fit in with my programs model and getting the user inputs is more difficult than expected, As no event is received by the window.

I checked with XCode the value of _currentEvent and it's consistently nil which leads me to think that the window isn't capturing the events in the first place. I included a screenshot of the window while it's focused, although it doesn't appear to be active as the icons aren't coloured. I've also included the code for the window creation in Objective-C

Note: Calling [application run] does work and I receive inputs with an active looking window once called.

Source: http://ift.tt/1JrC01D

Variables:

Variables

Window:

Window

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,

Slide Out Menu without a back Button

I use SWRevealViewController for my Slide Out Menu. I did actually the same like he did it here: https://www.youtube.com/watch?v=5SUV1YY2yxQ, but even I add a new ViewController and connect it with the segue "reveal view controller", start the app and click on the row to open the view controller, it will works, but I don't have a back Button. Why?

Can this dispatch_once singleton ever return nil?

Trying to find an issue we are experiencing intermittently, that seems to be occurring on devices with low memory conditions. The suspected cause is the NSDateFormatter singleton being nil.

Is there any possible situation where the singleton pattern below could return nil?

+ (NSDateFormatter *)dateFormatterUTC {

    static NSDateFormatter *formatter;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat=@"yyyy-MM-dd HH:mm:ss ZZZ";
    });

    return formatter;
}

Dynamic replaceable uiviewcontroller in side a view with bottom static menu ios

How will achieve the above with a bottom static menu and replaceable uiviewcontrollers like fragments in android in the middle part?

iOS Push Notifications handle

Looking for a good practice regarding push notifications handle. currently in my app i'm handling the push notifications in the didFinishLaunchingWithOptions and in the didReceiveRemoteNotification delegates. I noticed that both handling logics are "firing" when i receive a push notifications when the app is "Dead". My remote notifications flag in Background Modes is ON in my app. Is there a good practice for handling this scenario ? why am i getting the push data in the didFinishLaunchingWithOptions(launchOptions) and didReceiveRemoteNotification is getting called too ? to my knowledge the didReceiveRemoteNotification is not spoused to get called when the app is "Dead".

After tableview reload cell not deleted

I have one UIView and inside one table view.After reload data visible cell remains and overlapping another cell in table view.I am using pull to refresh control and using reloadRowsAtIndexPaths.

[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];

If I put something like this :

 if(indexPath.row >5){

                                             [self.tableView beginUpdates];
                                             [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                                             [self.tableView endUpdates];
                                         }
                                         else {

                                             [self.tableView reloadData];


                                         }

In this scenario there is no overlapping but this is not best solution.

iOS/ObjC: "Fallback" tap gesture recognizer?

I have a UIViewController subclass whose view will generally contain some number of UIButtons and other interactive elements which may have one or more gesture recognizes attached to them.

What I'm trying to do is provide some visual feedback in the event that the user taps on a part of the screen that is not interactive. In other words: when the user taps the screen anywhere, if and only if no other control in the view responds to the touch event (including if it's, say, the start of a drag), then I want to fire off a method based on the location of the tap.

Is there a straightforward way to do this that would not require my attaching any additional logic to the interactive elements in the view, or that would at least allow me to attach such logic automatically by traversing the view hierarchy?

It takes long time to fetch images (Objective-C)

I am a beginner ios developer and i want to create a photo album app. I find some codes from internet and try to learn from there. In the app, when i click an album, it takes so much time for the album's collectionview of images to load. To fetch the images, my code is in ViewWillAppear. Can you help me optimize this code for better performance. If there is more than 10-15 images, this takes so long to load. Thanks in advance and sorry if my English is bad.

-(void)viewWillAppear:(BOOL)animated
{
    // Call to the super classes implementation of viewWillAppear
    [super viewWillAppear:YES];
    /* The Photos are stored in Core Data as an NSSet. */
    NSSet *unorderedPhotos = self.album.photos;
    /* To organize them we use a NSSort descriptor to arrange the photos by date. */
    NSSortDescriptor *dateDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];
    NSArray *sortedPhotos = [unorderedPhotos sortedArrayUsingDescriptors:@[dateDescriptor]];
    self.photos = [sortedPhotos mutableCopy];

    /* Now that the photos are arranged we reload our CollectionView. */
    [self.collectionView reloadData];

}

Objective C: when valueForKey is an instance with properties

i am trying to extract a property of an instance of a class that is a property of another class! easier shown by example...

// Person is a class with properties: name and age
Person *person = [[Person alloc] init];
[person setName:@"Alex"];

// Age is a class with properties value (i.e. 100) and unit (i.e. year)
Age *age = [[Age alloc] init];
[age setValue:@100];
[person setAge:age];

NSMutableArray *people = [[NSMutableArray alloc] init];
[people addObject:person];

for (id person in people) {

how can i extract the value property of the age instance associated to the person?

    //[person valueForKey:@"age.value")];

i expect to get @100 - i get 'NSInvalidArgumentException'

this gives me the instance of Age - but i would rather have the value property.

    //[person valueForKey:@"age")];
}

is this possible? any help is much appreciated.

Add Object to NSMutableArray even it is check marked

I try to add the cell.textlabel.text to an NSMutableArray even it is check marked. I do this with following code:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    else{
        cell.accessoryType = UITableViewCellAccessoryCheckmark;

        self.selectedDays = [[NSMutableArray alloc] init];
        [self.selectedDays addObject:cell.textLabel.text];

        NSLog(@"%@", self.selectedDays);

    }
}

But it does not add, but replace.

    2015-06-28 xx:xx:xx xxxx - xxxx[xxx:xxx] (
    Monday
    )
    2015-06-28 xx:xx:xx xxxx - xxxx[xxx:xxx] (
    Tuesday
    )
    2015-06-28 xx:xx:xx xxxx - xxxx[xxx:xxx] (
    Wednesday
    )

How to push UIViewController from AppDelgate

I am building an iOS Application where there are 4 screen as - verify phone number,fb login, set your profile and home. Now what I need is that if a user have set her profile info and after clicking on next if he close the app. On the restarting of the app it should directly get navigated to the home screen and there should not be repetition of all the 3 screens again.

What happens is, the screen 1 ( verify phone no ) is shown for a short period of time and then home screen appears. I want home screen to appear immediately after the splash screen when I reopen the app.

I am using below code.

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UINavigationController *mvc = [storyboard instantiateViewControllerWithIdentifier:@"Home"];
    [self.window.rootViewController presentViewController:mvc animated:YES completion:nil];

importing swift framework into a objective-c project

I am importing swift framework into objective-c project like this:

@import MyFramework;

The problem is that only some of the classes are recognized by the class i am importing the framework.

The class which is recognized:

public class RecognizedClass:UIViewController, WKNavigationDelegate, WKScriptMessageHandle 
 { ... } 

The class which is not:

public class VeediUtils
{ ... } 

They are both public so why the first is recognized in the workspace and the other not?

Also i see in the header file MyFramework-Swift.h that a class

@interface RecognizedClass : UIViewController <WKNavigationDelegate, WKScriptMessageHandler>

Appear while the other dont

Why is that?

Also to point that this same procedure work when i am importing swift framework to swift project

Disable horizontal shift of webview content

I have the following code:

[myWebView.scrollView.panGestureRecognizer requireGestureRecognizerToFail:swipe];
[myWebView.scrollView.panGestureRecognizer requireGestureRecognizerToFail:swipe2];

which disables mywebview to scroll horizontaly. Instead it should perform an other method after swiping. It works with iOS 8+ but in iOS 7.1 the content of the webview still gets "scrolled" horizontally. I´ve attached a screenshot to illustrate my problem. I don´t want the gray area on the right to happen:

http://ift.tt/1ID2E1V

As you can see not the whole content is shiftet to the left. How can I prevent this "inner" horizontal shift and perform instead a method while swiping to the left? Thx.

Is it possible to use the location indicator outside MKMapView?

Does anyone know if it's possible to use the little blue dot outside the context of an MKMapView (and if so how)?

I've seen it done in a few other apps, however I don't know whether they've just tried to manually recreate it or whether the component is available. I tried searching online, but I don't actually know the name of the component which is making it very challenging.

enter image description here

How to debug uncaught NSRange exception in Xcode?

I am getting the following exception. How can I find from looking at this as to where I am having a problem with my NSArray

*** Terminating app due to uncaught exception 'NSRangeException', reason:

'*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000109ba4a75 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010983dbb7 objc_exception_throw + 45
    2   CoreFoundation                      0x0000000109a9c97e -[__NSArrayI objectAtIndex:] + 190
    3   UIKit                               0x00000001076bd506 -[UITableViewDataSource tableView:heightForRowAtIndexPath:] + 109
    4   UIKit                               0x00000001073f0afb __66-[UISectionRowData refreshWithSection:tableView:tableViewRowData:]_block_invoke + 302
    5   UIKit                               0x00000001073f018e -[UISectionRowData refreshWithSection:tableView:tableViewRowData:] + 4125
    6   UIKit                               0x00000001073f250b -[UITableViewRowData _ensureSectionOffsetIsValidForSection:] + 131
    7   UIKit                               0x00000001073f56f5 -[UITableViewRowData rectForFooterInSection:heightCanBeGuessed:] + 352
    8   UIKit                               0x00000001073f57ca -[UITableViewRowData heightForTable] + 56
    9   UIKit                               0x000000010724e553 -[UITableView _adjustExtraSeparators] + 216
    10  UIKit                               0x00000001072637b2 -[UITableView layoutSubviews] + 251
    11  UIKit                               0x00000001071f01c3 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 521
    12  QuartzCore                          0x0000000108ad1c58 -[CALayer layoutSublayers] + 150
    13  QuartzCore                          0x0000000108ac687e _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
    14  QuartzCore                          0x0000000108ac66ee _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    15  QuartzCore                          0x0000000108a3436e _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
    16  QuartzCore                          0x0000000108a35482 _ZN2CA11Transaction6commitEv + 390
    17  QuartzCore                          0x0000000108a35aed _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 89
    18  CoreFoundation                      0x0000000109ad9507 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    19  CoreFoundation                      0x0000000109ad9460 __CFRunLoopDoObservers + 368
    20  CoreFoundation                      0x0000000109acf293 __CFRunLoopRun + 1123
    21  CoreFoundation                      0x0000000109acebc6 CFRunLoopRunSpecific + 470
    22  GraphicsServices                    0x000000010a460a58 GSEventRunModal + 161
    23  UIKit                               0x0000000107176580 UIApplicationMain + 1282
    24  APP_NAME                            0x0000000106d0dfc3 main + 115
    25  libdyld.dylib                       0x000000010aa68145 start + 1
    26  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Objective-C dot accessor behaves differently with implicit getter

Can one of you kind people please help me to understand why I get '(null)' for the second line in the output but not the fourth? Many thanks in advance

MyClass.h

@interface MyClass : NSObject
@property (readonly) NSString *foo;
@property (getter=getBar, readonly) NSString *bar;
@end

main.m

@implementation MyClass
- (NSString *)getFoo { return @"foo"; }
- (NSString *)getBar { return @"bar"; }
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {     
        MyClass *myClassInstance = [MyClass new];

        NSLog(@"%@", myClassInstance.getFoo);
        NSLog(@"%@", myClassInstance.foo);

        NSLog(@"%@", myClassInstance.getBar);
        NSLog(@"%@", myClassInstance.bar);
    }
    return 0;

output

foo
(null)
bar
bar

Send a busy signal when the app is in another call

I am using twilio iOS SDK. Is it possible to send a busy signal from the app if it is in another call?

Query PFRelation of blocked users

I'm trying to query the 'friend' relation while excluding any friends that have blocked the user (which is stored as a relation<_user>) on the friends user with a relation to the user they are blocking (potentially the user checking their friends). I tried querying like below, but it isn't excluding the record like I would think:

[SVProgressHUD showWithStatus:@"Loading ..."];

[friends removeAllObjects];

PFRelation *friendRelation = [[PFUser currentUser] objectForKey:@"friendsRelation"];
if (friendRelation)
{
PFQuery *friendsQuery = [friendRelation query];
    [friendsQuery orderByAscending:@"firstname"];
    [friendsQuery whereKey:@"disabled" notEqualTo:[NSNumber numberWithBool:YES]];
    [friendsQuery whereKey:@"Blocked" notEqualTo:[PFUser currentUser]];
[friendsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)
 {
     if (!error)
     {
         friends = [objects mutableCopy];
         [self.myTableView reloadData];
         [SVProgressHUD dismiss];
     }
     else
     {
         [SVProgressHUD showErrorWithStatus:@"Loading failed. Please try again."];
     }
 }];
}
else
{
    [SVProgressHUD dismiss];
}

Is there a way to accomplish what I am trying to do?

is it able to override NSObject init method to add every object into a single NSMutableArray?

I have a singleton object obj1, having a NSMutableArray member called Objects

and i added a category called NSObject (Register)

@implementation NSObject (Register)
-(id)init
{
    [[obj1 defaultObject] addObjectToView:self];
    return self;
}
@end

the addObjectToView method just simply add the object to the array

-(void)addObjectToView:(id)object
{
    [object retain];
    [Objects addObject:object];
}

(Object is a NSMutableArray)

the problem is, when i tried to test it, i did

NSWindow *window = [[NSWindow alloc] init];

and then i got 505 scary objects in the array,

(sorry, unable to post image) http://ift.tt/1QWWq6G

did i do anything wrong?

BTW, it is possible to manage the relationship of all objects and send isolate objects dealloc message to implement a garbage collector in Objective-C ?

Parse object containing array elements

I have a Parse object called Recipes and a column called ingredients, which is an array. I want to query my object list and retrieve a recipe based on some ingredients that I select.

If I use the whereKey:containsAllObjectsInArray: message on the query object, I will get recipes with more ingredients. Also, whereKey:containedIn: does not solve my problem. The retrieved objects should have an array of ingredients containing all my selected ingredients or only some of them. It should never have more ingredients than those I've selected.

Any ideas?

call class method within a framework

In objective-c how can i call class method inside a framework?

This is the method declaration:

public class func setGameLevel(level:Int)
{
    current_level = level
}

That is the class declaration (of the framework class):

public class MyClass
{

I imported the framework, now how can i call the method setGameLevel of the MyClass method?

In swift its called using:

MyClass.setGameLevel(1)

EXC_BAD_ACCESS tapping uisearchbar three times

I am trying to implement a search bar in a UICollectionView as a UICollectionViewReusableView

This way I am not using a UISearchController but I am changing the datasource of the collectionview

In my custom layout I am adding the searchbar this way:

override func prepareLayout() {
    super.prepareLayout()
    var searchBarAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: TeacherSearchbarIdentifier, withIndexPath: NSIndexPath(forItem: 0, inSection: 0))
    searchBarAttributes.frame = CGRectMake(0, 0, collectionViewContentSize().width, 44)
    searchBarAttributes.zIndex = 100
    miscAttributes.append(searchBarAttributes)
}

override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
    var attributes = [UICollectionViewLayoutAttributes]()
    for (idx, attr) in enumerate(miscAttributes) {
        if CGRectIntersection(rect, attr.frame) != CGRectNull {
            attributes.append(attr)
        }
    }

    return attributes
}

I am setting the delegate like this:

func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    var view = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: kind, forIndexPath: indexPath) as! UICollectionReusableView
    if kind == TeacherSearchbarIdentifier {
        controller.searchBar = (view as! TeacherSearchView).searchBar
        return view
    }
}

The variable controller is the UICollectionViewController which implements the UISearchBarDelegate Protocol

The delegate is set in didSet of the searchBar variable. These are my delegates:

override func scrollViewDidScroll(scrollView: UIScrollView) {
    self.view.endEditing(true)
}

func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
    searchBar.setShowsCancelButton(true, animated: true)
    return true
}

func searchBarShouldEndEditing(searchBar: UISearchBar) -> Bool {
    searchBar.setShowsCancelButton(false, animated: true)
    searchBar.resignFirstResponder()
    return true
}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    searchBar.setShowsCancelButton(false, animated: true)
    searchBar.resignFirstResponder()
}

Now my problem!

When I am tapping on the search bar, the keyboard appears. If I press the cancel button or scroll, it dissappears. Just as I want it to. This also works a second time.

BUT!

If I do this a third time, I get a EXC_BAD_ACCESS:

EXC_BAD_ACCESS (code=1, address=0x14ac0beb8)

I tried turning on Enabling Zombie Objects, but no information was provided. I also tried profiling for Zombie Objects, it just crashes without any noticeable information.

Please help me on how I can resolve this error, or give me further debugging instructions.

Displaying NSMutable array using User Defaults

I am working on an app that has a mutable array of custom object ToDoItem(kind of morphed the dev example into my own app, will change later). I know its not the best way to do it, but I am using the user defaults to save it. Now, in the commented out code at the top, simply calling "addObject" loads the info into the table view. I don't know the intricacies of how this works, can somebody please explain why nothing is loading to the table view when I load it from user defaults? I am a beginner, so please explain thoroughly. Thank you for any help!

@interface ToDoListTableViewController ()
@property NSMutableArray *toDoItems;

@end

@implementation ToDoListTableViewController
- (void)loadInitialData1 {

   /*
ToDoItem *item1 = [[ToDoItem alloc] init];
item1.location = @"BDK";
item1.total = [[NSNumber alloc] initWithFloat:15.0];
item1.tip = [[NSNumber alloc] initWithFloat:5.567];
item1.percentage = [[NSNumber alloc] initWithFloat:33.0];
[self.toDoItems addObject:item1];
ToDoItem *item2 = [[ToDoItem alloc] init];
item2.location = @"Emrick";
item2.total = [[NSNumber alloc] initWithFloat:10.0];
item2.tip = [[NSNumber alloc] initWithFloat:2.0];
item2.percentage = [[NSNumber alloc] initWithFloat:20.0];
[self.toDoItems addObject:item2];
ToDoItem *item3 = [[ToDoItem alloc] init];
item3.location = @"PPM";
item3.total = [[NSNumber alloc] initWithFloat:20.0];
item3.tip = [[NSNumber alloc] initWithFloat:20.0];
item3.percentage = [[NSNumber alloc] initWithFloat:100.0];
[self.toDoItems addObject:item3];
*/


self.toDoItems = [[[NSUserDefaults standardUserDefaults]objectForKey:@"key"]mutableCopy];

}

- (IBAction)unwindToList:(UIStoryboardSegue *)segue {
AddToDoItemViewController *source = [segue sourceViewController];
ToDoItem *item = source.toDoItem;
if (item != nil) {

    [self.toDoItems addObject:item];
    [self.tableView reloadData];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [defaults setObject:self.toDoItems forKey:@"key"];

    [defaults synchronize];

    NSLog(@"Data saved");

    }
}

MySQL server and iOS

I run a site write now with a quite big MySQL database. Now, I want to create an app. I will need to use obviously a database de to the fact my data are already there.

Thus,

1) Should I keep using the MySQL server and my iOS app will connect to this MySQL serve for getting data?

2) is there any problem if I use the MySQL server ? Security issues maybe?

3) if I have to change the MySQL server, what database infrastructure I need to build and work with?

I am totally newbie on iOS apps. And now I planning to face any issues my iOS app will have.

Google map cocoa pods integration issue

Hi I am integrating google maps with cocoa pods. I have done the integration but when i an running the project I Am getting following issue

ld: warning: Auto-Linking supplied '/Users/SANDY/Robert/Office/ProjectName/Pods/GoogleMaps/Frameworks/GoogleMaps.framework/GoogleMaps', framework linker option at /Users/SANDY/Robert/Office/ProjectName/Pods/GoogleMaps/Frameworks/GoogleMaps.framework/GoogleMaps is not a dylib
Undefined symbols for architecture i386:
  "_OBJC_CLASS_$_GMSCameraPosition", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSCameraUpdate", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSCoordinateBounds", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSMapView", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSMarker", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSPath", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSPolyline", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSServices", referenced from:
      objc-class-ref in EzAppDelegate.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Thanks for help in advance.

How to wake iphone on applewatch programmaticlly

So my scenario is control iphone music player on applewatch. Just like what the applewatch music glance would do. The project is gonna be iphone app, watch app, and watch extension. however, I want it to be able to work even thou my iphone app is not active. I know when iphone app is active, I could use wcsession and sendMessage to control the music on iphone. However, when the iphone app is not active. I don't know what I should do to get the work done. Any ideas?

One more thing, I am newbie to objective-c and ios, therefore, I don't understand how iphone app works when it is not active. Does it need to be active first do those job, or it is never really inactive so it could still do work, if anyone could tell me about that would be great as well.

simple CoverFlow example in objective C

can you please provide me with a simple coverflow sample code, I am trying to find some, but all examples are complex and contain unwanted details.

How to show ProgressBar With AFNetworking AFHTTPRequestOperationManager

I am trying to show the Progress Bar as I download a JSON from a url. The JSON is downloading correctly but I am not sure how to show the Progress Bar. I have tried using UIProgressView but it does not display on the screen. Any suggestions would be appreciated.

CGFloat width = [UIScreen mainScreen].bounds.size.width;
CGFloat height = [UIScreen mainScreen].bounds.size.height;

CGRect rect = CGRectMake(width/2, height/2, width/5, height/5);
UIProgressView *myProgressView = [[UIProgressView alloc]initWithFrame:rect];
myProgressView.progressViewStyle = UIProgressViewStyleBar;
[self.view addSubview:myProgressView];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];    
[manager GET:@"https:urlWithJson" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
      [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
       {
           myProgressView.progress = (float)totalBytesRead / totalBytesExpectedToRead;
       }];
      [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
          NSLog(@"operation Completed");
      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          NSLog(@"ERROR");
      }];

      [operation start];
  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      NSLog(@"timeout Error: %@", error);
  }];

Creating a Bridging Header

I am creating a Bridging Header manually since it doesn't let me do it automatically. I created the a header file called "AppName-Bridging-Header.h. The problem is that I can not set it as the project’s Bridging header, which can be normally done through the project’s build settings. I do not have the Objective-C Bridging file section under Swift Compiler -Code generation. I only have Optimization level. Thank you.

Importing swift written framework to project written in objective-c

I wrote a cocoa touch framework in swift code

Test.framework

In this framework i can see files Test.h and test-Swift.h

I am now trying to import it to an objective c project.

Put the file in the project folder and in build phases i added the framework to "Link Binary With Libraries" and "Copy Bundle Resources"

Now i am not sure about ho to do it but when i try to import the fraqmework in the ViewController.m class like this:

#import "Test-Swift.h"

It gives me file not found error

BTW when creating new Swift project and doing the same it works

IOS optimization using time profiler and Core Animation

So I have an app, in which I use custom UIView. There are other UIView, which are subviews of that view. All of them have pan gesture recognizers, so that the user can pan them in the specific fashion. When I test my app using one such view all is well and good, it is all smooth and fps is around 55-60. However, when I add the second one(somewhat smaller then the first one, and kinda inside first one, but not as a subview). The FPS of the outer views drops to 20-30, while the inner one(which is smaller) works in 60 fps. This two views are ABSOLUTELY independent, meaning that interacting with one doesn't affect the other one. In addition to that, I checked running time on the interval of one second, the results are the following: For 1 view: 153ms For 2 views 145ms For 3 views 150ms

The calculations that are performed on each view are ABSOLUTELY identical in complexity. Why does one work smoothly, but when I add the second one it starts to lag, while the execution time stays the same ? I would appreciate if somebody could hint me at how I should debug it.

The most consuming operation according to the Time Profiler is repositioning one of the views:

view.center = newCenter

I simply can't understand why FPS drops 2-3 times, while the running time stays the same. What should I look for ?

UPDATE:

So I found the source of the problem, when one view is inside the frame of the other the whole thing is being constantly redrawn, even though no changes were made to the layout of the inner view. So when I positioned a few of them in different parts of the screen everything was fine, but when I put one "inside" the other things get messed up. Inner one works quickly, while the outer one lags. "Flash updated regions" flag in core animation show that when I interact with outer view, inner view gets updated as well. Any suggestions on what I might need to do, because I need that layout when they are one inside each other. So how can I prevent(lock) other view from redrawing ?

Thank You.

Passing Facebook login information to the second view

This is a 2 part question.

1.) Once the user login to the application i want to navigate to DashboardViewController. However, i am ending up with a warning.

Warning: Attempt to present on whose view is not in the window hierarchy!

How to solve this?

2.) I want to pass (id<FBGraphUser>)user to the DashboardViewController, How can i achieve this?

The code is as follows:

-(void)viewWillAppear:(BOOL)animated{
    //[self toggleHiddenState:YES];
    self.lblLoginStatus.text = @"";

    self.loginButton.delegate = self;
    self.loginButton.readPermissions = @[@"public_profile", @"email"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Private method implementation

-(void)toggleHiddenState:(BOOL)shouldHide{
    self.lblUsername.hidden = shouldHide;
    self.lblEmail.hidden = shouldHide;
    self.profilePicture.hidden = shouldHide;
}


#pragma mark - FBLoginView Delegate method implementation

-(void)loginViewShowingLoggedInUser:(FBLoginView *)loginView{



    self.lblLoginStatus.text = @"You are logged in.";

    [self toggleHiddenState:NO];
}



-(void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user{
    NSLog(@"%@", user);
    self.profilePicture.profileID = user.objectID;
    self.lblUsername.text = user.name;
    self.lblEmail.text = [user objectForKey:@"email"];
//

    [self performSelector:@selector(displayDashboard) withObject:nil afterDelay:0.5];

}

-(void)displayDashboard{
    DashboardViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"DashboardSegue"];

    [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:vc animated:YES completion:nil];
}




-(void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView{
    self.lblLoginStatus.text = @"You are logged out";

    [self toggleHiddenState:YES];
}


-(void)loginView:(FBLoginView *)loginView handleError:(NSError *)error{
    NSLog(@"OKKKKK %@ ", [error localizedDescription]);

}


@end

Create forget password functionality using AWS EC2

I'm currently thinking of the process on how to create a "Forget Password" functionality for my app. I have not use AWS EC2 service before so I want to know how can I go about doing it or is there a sample tutorial for me to look at?

Thanks!

Is there a perfect way to use iOS Framework template instead of static library now?

Since iOS8 and Xcode6 has release for a year, I have still cannot find a canonical tutorial for using Framwork template (iOS Universal Framework Mk 8) to develope a static library.

enter image description here

Even though the most popular Repo I think, kstenerud/iOS-Universal-Framework, has shut down when iOS8 Framework release.

enter image description here


However, when I try to develope a Static Framework I got ton of issues to resolve:

  1. I still have to do lipo for x86_64, i386, arm64, amrv7;
  2. remove Code signature from Framework;
  3. Build a resource bundle and import it to app project independent;
  4. Framework Info.plist and modules seem useless;
  5. Still a little worried if Apple will refuse my app since use a Static Framework.

Is there a good tutorial for building and using Static Framework? Any help will be appreciated! Thx.

I get error when I add a UITableView

I have a static UITableView, and in one of the cells, I have a dynamic UITableView. Here is the code I used:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;

    if (self.tableView == tableView) {
        cell = [tableView cellForRowAtIndexPath:indexPath];
    }
    else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        [cell.textLabel setText:self.tagsArray [indexPath.row]];
    }
    return cell;
}

When I run the app, it crashes with the following error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000106efbc65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000106b94bb7 objc_exception_throw + 45
    2   CoreFoundation                      0x0000000106efbaca +[NSException raise:format:arguments:] + 106
    3   Foundation                          0x00000001067a998f -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195
    4   UIKit                               0x000000010762fa83 -[UITableView _configureCellForDisplay:forIndexPath:] + 128
    5   UIKit                               0x0000000107637a41 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 533
    6   UIKit                               0x0000000107616248 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2853
    7   UIKit                               0x000000010762c8a9 -[UITableView layoutSubviews] + 210
    8   UIKit                               0x00000001075b6a2b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 536
    9   QuartzCore                          0x0000000106588ec2 -[CALayer layoutSublayers] + 146
    10  QuartzCore                          0x000000010657d6d6 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
    11  QuartzCore                          0x000000010657d546 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    12  QuartzCore                          0x00000001064e9886 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
    13  QuartzCore                          0x00000001064eaa3a _ZN2CA11Transaction6commitEv + 462
    14  QuartzCore                          0x00000001064eb0eb _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 89
    15  CoreFoundation                      0x0000000106e2eca7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    16  CoreFoundation                      0x0000000106e2ec00 __CFRunLoopDoObservers + 368
    17  CoreFoundation                      0x0000000106e24a33 __CFRunLoopRun + 1123
    18  CoreFoundation                      0x0000000106e24366 CFRunLoopRunSpecific + 470
    19  GraphicsServices                    0x000000010ad61a3e GSEventRunModal + 161
    20  UIKit                               0x0000000107536900 UIApplicationMain + 1282
    21  myBudget                            0x000000010611fe5f main + 111
    22  libdyld.dylib                       0x0000000108952145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Why do I get this error, and what can I do to fix it?

How to retrieve part of JSON file?

it's possible by using IF to retrieve some parts of JSON not all of it in Objective-C. like i want to retrieve just those data when Gender equals Male

[
  {
    "name":"A",
    "gender":"Male",
    "age":20
  },
  {
    "name":"B",
    "gender":"Female",
    "age":12
  },
 {
    "name":"C",
    "gender":"Male",
    "age":20
  }
]

any idea would be appreciated.

samedi 27 juin 2015

Changing the status bar color on UISearchController

I'm trying to change iOS 8 search bar status bar color but I tried the UIStatusBarStyleLightContent with no luck anyone knows a better way? Example of how it looks right now

Get the number of lines in UILabel iOS8

I'm seeing lots of deprecated answers for this question:

How do I calculate the number of lines in use in a UILabel based of its set text?

I know that I need to set the UILabel to have bounds that resize with word wrapping. In this way, I could detect the height of my UILabel and adjust an NSLayoutConstraint for the height of my UITableViewCell. Basically my problem plain and simple is:

How can I determine my UILabel's number of lines in use(based of descriptionLabel.text) or height in order to resize My UITableView's UITableViewCells which contain my UILabel.

Currently I have used this code:

descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 30, 270, 65)];
descriptionLabel.textColor = [UIColor blackColor];
descriptionLabel.numberOfLines = 0;
descriptionLabel.adjustsFontSizeToFitWidth = YES;

What is the point of a nil AutoreleasingUnsafeMutablePointer in a Swift closure?

I was reading the different ways to parse REST API calls in Swift and came across the following:

var url : String = "http://ift.tt/1tENtnZ"
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
    var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
    let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

    if (jsonResult != nil) {
        // process jsonResult
    } else {
       // couldn't load JSON, look at error
    }


})

The one line that makes no sense to me is var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil. We already captured our NSError parameter and stored it in a variable called error, and now we're overwriting that and making it nil in our first line in the closure? Or if somehow Swift then performs a downcast of the error from type NSError! to AutoreleasingUnsafeMutablePointer<NSError?>, then can someone explain how that happens?

Thanks!

UITextInputCurrentInputModeDidChangeNotification return nill in ios 8.3

I want to detect current input mode of keyboard, and change text direction with respect to it (rtl if arabic, and ltr if english) in viewDidLoad:

- (void)viewDidLoad {
[super viewDidLoad];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(changeInputMode:)
                                             name:UITextInputCurrentInputModeDidChangeNotification object:nil];

} and in changeInputMode:

-(void)changeInputMode:(NSNotification *)notification
{
    UITextInputMode *thisInputMode = [notification object];

    NSLog(@"inputMethod=%@",thisInputMode);
}

but thisInputMode is nill! if I use this code instead:

    NSString *inputMethod = [[UITextInputMode currentInputMode] primaryLanguage];
    NSLog(@"inputMethod=%@",inputMethod);

it works fine and detects current password, but currentInputMode is deprecated. why [notification object] returns nill?

Add lines on ImageView IOS (objective c)

enter image description here

I need some help to get this thing working..

Basically on button click, I have to add a line of fixed width with circle end points on the ImageView. User can add upto 5 lines. If I click on any circle (red dot) end point of line, it should allow to resize the line. Point can be dragged to any position on screen and line has to be straight. At the end, i should be able to calculate the length of each line. I just spent a lot of time on this and referring other similar answers. But so far, no luck.. Any reference code or links is greatly appreciated. Thanks!

IOS resize or reposition line on touching end points (Objective c)

I am trying to resize the line, by touching the red circle points. Let's say, I want to move this line above lips in the image below, How can i achieve this. The line is not moving from the position. I have just started up with this thing and can't find much relevant resources to accomplish this. Trying the best...Please guide me in the right direction. Below is my code and reference image.

Objective c code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 100) radius:10 startAngle:0 endAngle:6.2831853 clockwise:TRUE];

    //Add second circle
    [path moveToPoint:CGPointMake(100.0, 100.0)];
    [path addLineToPoint:CGPointMake(200, 200)];
    [path moveToPoint:CGPointMake(200, 200)];

    [path addArcWithCenter:CGPointMake(200, 200) radius:10 startAngle:0 endAngle:6.2831853 clockwise:TRUE];


    [path closePath];
    [[UIColor redColor] setStroke];
    [[UIColor redColor] setFill];
    [path stroke];
    [path fill];

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [path CGPath];
    shapeLayer.strokeColor = [[UIColor blueColor] CGColor];
    shapeLayer.lineWidth = 2.0;
    shapeLayer.fillColor = [[UIColor redColor] CGColor];

    [self.view.layer addSublayer:shapeLayer];

}

enter image description here

I will add multiple lines like this and my ultimate aim is to move individual line at any position in the image and get measurement of that area using line size.

EDIT: The scenario is, at any given time there will be some flexible lines available on the screen. Lets's say by clicking button, one more new line will be added to screen. The user can just drag any end point to resize the line in any direction. I can't get this thing working correctly.. no luck.

Here is my gist file link, http://ift.tt/1dp9Hm0 It basically adds a UIView to create a line on image. The code in gist allows me to resize the line height by moving touch points up and down but doesn't allow me to rotate the angle of line and adding text in the centre. THANKS

Thanks!

How to get all the classes of an application specified with identifier in iOS?

I want to get all the classes of a specified application (maybe any other apps, not only the app itself), I can get the NSBundle of that application with it's identifier, but how can I get the classes with the NSBundle, or can I get the classes directly with the application's identifier? We assume it could be a jailbroken environment.I tryied objc_copyClassNamesForImage but failed, does any one have ideas? Any help will be appreciated!

NSBundle * bundle = [NSBundle bundleWithIdentifier:appIdentifier];
NSString * bundlePath = [bundle bundlePath];
NSLog(@"%@", bundlePath);

unsigned int count;
const char **classes;

classes = objc_copyClassNamesForImage([bundlePath UTF8String], &count);

for (int i = 0; i< sizeof(classes)/sizeof(classes[0]); i++){
    NSLog(@"class name: %s", classes[i]);
}

IOS line measurement on picture

I need some help to get started on drawing lines with circle at ends, and measure its length. I am able to draw the line but can't make it moving,having spent hours decided to post on SO.

So please see below image and guide me to get started. Any sample or tutorial using objective c will help.

enter image description here

Thanks :)

Parse Relation [Error]: can't add a non-pointer to a relation (Code: 111, Version: 1.7.5)

I have a jobs app that enables users to view jobs. Jobs is a class in my Parse backend. I want to create a Favorites tab where user can mark certain jobs.

I've created a Relations Column in my User Class referring it to my Jobs class.

However, I have ran into this when the user taps to make the job a favorite: [Error]: can't add a non-pointer to a relation (Code: 111, Version: 1.7.5)

I feel like my PFRelation coding is spot on. I've researched this error but cannot seem to find any subject that relates to my problem. I must be making a mistake somewhere but

@interface JobDetailViewController ()

@end

@implementation JobDetailViewController

@synthesize jobPhoto;
@synthesize RotationLabel;
@synthesize QualificationsTextView;
@synthesize Job_DescriptionTextView;
@synthesize TypeLabel;
@synthesize LocationLabel;
@synthesize ClearanceLabel;
@synthesize PositionLabel;
@synthesize job;
@synthesize POC;
@synthesize Email;
@synthesize Phone;
@synthesize Apply;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [_Scroller setScrollEnabled:YES];
    [_Scroller setContentSize:CGSizeMake(320, 2200)];

    [self dismissKeyboard];
    self.PositionLabel.text = job.position;
    self.RotationLabel.text = job.rotation;
    self.LocationLabel.text = job.location;
    self.TypeLabel.text = job.type;
    self.ClearanceLabel.text = job.clearance;
    jobPhoto.file = (PFFile *)job.imageFile;
    [jobPhoto loadInBackground];

    NSMutableString *pocText = [NSMutableString string];
    for (NSString* poc in job.poc) {
        [pocText appendFormat:@"%@\n", poc];
    }
    self.POC.text = pocText;

    NSMutableString *emailText = [NSMutableString string];
    for (NSString* email in job.email) {
        [emailText appendFormat:@"%@\n", email];
    }
    self.Email.text = emailText;


    NSMutableString *phoneText = [NSMutableString string];
    for (NSString* phone in job.phone) {
        [phoneText appendFormat:@"%@\n", phone];
    }
    self.Phone.text = phoneText;

    NSMutableString *applyText = [NSMutableString string];
    for (NSString* apply in job.apply) {
        [applyText appendFormat:@"%@\n", apply];
    }
    self.Apply.text = applyText;

    NSMutableString *qualificationsText = [NSMutableString string];
    for (NSString* qualifications in job.qualifications) {
        [qualificationsText appendFormat:@"%@\n", qualifications];
    }
        self.QualificationsTextView.text = qualificationsText;

    NSMutableString *job_descriptionText = [NSMutableString string];
    for (NSString* job_description in job.job_description) {
        [job_descriptionText appendFormat:@"%@\n", job_description];
    }
    self.Job_DescriptionTextView.text = job_descriptionText;
}



- (IBAction)favoriteButtonAction:(id)sender {
    PFObject *jobs = [PFObject objectWithClassName:@"Jobs"];
    PFUser *user = [PFUser currentUser];
    PFRelation *relation = [user relationForKey:@"Favorites"];
    [relation addObject:jobs];

    [user saveInBackground];



}


- (void)viewDidUnload
{
    [self setJobPhoto:nil];
    [self setPositionLabel:nil];
    [self setRotationLabel:nil];
    [self setLocationLabel:nil];
    [self setTypeLabel:nil];
    [self setQualificationsTextView:nil];
    [self setJob_DescriptionTextView:nil];
    [self setPOC: nil];
    [self setPhone:nil];
    [self setEmail:nil];
    [self setApply:nil];
    [self dismissKeyboard];

    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

-(void) dismissKeyboard {
    [Email resignFirstResponder];
    [POC resignFirstResponder];
    [Phone resignFirstResponder];
    [Job_DescriptionTextView resignFirstResponder];
    [QualificationsTextView resignFirstResponder];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
 return NO;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void) favoriteSuccess {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success!" message:@"Added job to Favorites!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}


- (void) favoriteFailed {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ooooops!" message:@"Error occurred while adding to Favorites!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}



@end

JobListViewController that populates the jobs prior to the JobDetailViewController:

#import "JobDetailViewController.h"
#import "JobListViewController.h"
#import "Job.h"
#import "SearchedResultCell.h"
#import <Parse/Parse.h>



@interface JobListViewController () <UISearchDisplayDelegate, UISearchBarDelegate> {

}

@property (nonatomic, weak) IBOutlet UISearchBar *searchedBar;
@property (nonatomic, strong) NSString *mainTitle;
@property (nonatomic, strong) NSString *subTitle;
@property (nonatomic, assign) BOOL canSearch;

@end

    @interface JobListViewController ()

    @end

    @implementation JobListViewController
    {}
    @synthesize searchedBar;
    @synthesize mainTitle;
    @synthesize subTitle;
    @synthesize canSearch;


    - (id)initWithCoder:(NSCoder *)aCoder
    {
        self = [super initWithCoder:aCoder];
        if (self) {
            // Custom the table

            // The className to query on
            self.parseClassName = @"Jobs";

            // The key of the PFObject to display in the label of the default cell style
            self.textKey = @"Position";

            // Whether the built-in pull-to-refresh is enabled
            self.pullToRefreshEnabled = YES;

            // Whether the built-in pagination is enabled
            self.paginationEnabled = YES;

            // The number of objects to show per page
            self.objectsPerPage = 20;
        }
        return self;
    }

    - (void)viewDidLoad
    {
        [super viewDidLoad];



    }

    - (void)viewWillAppear:(BOOL)animated {
        [super viewWillAppear:animated];

        self.canSearch = 0;

    }

    - (void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
    }

    - (void)viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
    }

    - (void)viewDidDisappear:(BOOL)animated {
        [super viewDidDisappear:animated];
    }

    - (void)viewDidUnload
    {
        [super viewDidUnload];
        // Release any retained subviews of the main view.
    }

    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    }

    - (void)objectsWillLoad {
        [super objectsWillLoad];

        // This method is called before a PFQuery is fired to get more objects
    }


    - (PFQuery *)queryForTable
    {
        PFQuery *query1 = [PFQuery queryWithClassName:@"Jobs"];
        NSString *searchThis = [searchedBar.text capitalizedString];
        [query1 whereKey:@"Position" containsString:searchThis];
        PFQuery *query2 = [PFQuery queryWithClassName:@"Jobs"];
        [query2 whereKey:@"Type" containsString:searchThis];
        PFQuery *query = [PFQuery orQueryWithSubqueries:@[query1,query2]];
            [query orderByDescending:@"createdAt"];

        if (self.pullToRefreshEnabled) {
            query.cachePolicy = kPFCachePolicyNetworkOnly;
        }

        // If no objects are loaded in memory, we look to the cache first to fill the table
        // and then subsequently do a query against the network.

        return query;
    }







    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object: (PFObject *)object
    {
        static NSString *simpleTableIdentifier = @"JobCell";
            static NSString *pimpleTableIdentifier = @"JobCell";

        UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];

        SearchedResultCell *bell = [self.tableView dequeueReusableCellWithIdentifier:pimpleTableIdentifier];

        if (bell == nil) {
            bell = [[SearchedResultCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:pimpleTableIdentifier];

            }

            [self configureSearchResult:bell atIndexPath:indexPath object:object];


        }

        // Configure the cell
        PFFile *thumbnail = [object objectForKey:@"imageFile"];
        PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
        thumbnailImageView.image = [UIImage imageNamed:@"AppIcon.png"];
        thumbnailImageView.file = thumbnail;
        [thumbnailImageView loadInBackground];

        UILabel *positionLabel = (UILabel*) [cell viewWithTag:101];
        positionLabel.text = [object objectForKey:@"Position"];
        UILabel *rotationLabel = (UILabel*) [cell viewWithTag:102];
        rotationLabel.text = [object objectForKey:@"Rotation"];
        UILabel *locationLabel = (UILabel*) [cell viewWithTag:103];
        locationLabel.text = [object objectForKey:@"Location"];
        UILabel *typeLabel = (UILabel*) [cell viewWithTag:104];
        typeLabel.text = [object objectForKey:@"Type"];


    return cell;
    }


    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
        if ([segue.identifier isEqualToString:@"showJobDetail"]) {
            NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];

            Job *job = [[Job alloc] init];

            JobDetailViewController *destViewController = segue.destinationViewController;

            PFObject *object = [self.objects objectAtIndex:indexPath.row];
            job.position = [object objectForKey:@"Position"];
            job.poc = [object objectForKey:@"POC"];
            job.email = [object objectForKey:@"Email"];
            job.phone = [object objectForKey:@"Phone"];
            job.apply = [object objectForKey:@"Apply"];
            job.imageFile = [object objectForKey:@"imageFile"];
            job.rotation = [object objectForKey:@"Rotation"];
            job.location = [object objectForKey:@"Location"];
              job.type = [object objectForKey:@"Type"];
            job.clearance = [object objectForKey:@"Clearance"];
            job.job_description = [object objectForKey:@"Job_Description"];
            job.qualifications = [object objectForKey:@"Qualifications"];
            destViewController.job = job;

        }

    }

    - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
    {

        [self clear];

        self.canSearch = 1;

        [self.searchedBar resignFirstResponder];

        [self queryForTable];
        [self loadObjects];

    }



    - (void)configureSearchResult:(SearchedResultCell *)cell atIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
    {
        mainTitle = [object objectForKey:@"Position"];
        cell.mainTitle.text = mainTitle;

        subTitle = [object objectForKey:@"Type"];
        cell.detail.text = subTitle;

         // Implement this if you want to Show image
         cell.showImage.image = [UIImage imageNamed:@"AppIcon.png"];

         PFFile *imageFile = [object objectForKey:@"imageFile"];

         if (imageFile) {
         cell.showImage.file = imageFile;
         [cell.showImage loadInBackground];
         }
    }


    #pragma mark - UITableViewDelegate

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {



        [tableView deselectRowAtIndexPath:indexPath animated:YES];

        [searchedBar resignFirstResponder];

        if ([self.objects count] == indexPath.row) {
            [self loadNextPage];
        } else {
            PFObject *photo = [self.objects objectAtIndex:indexPath.row];
            NSLog(@"%@", photo);

            // Do something you want after selected the cell
        }
    }



    #pragma mark - UIScrollViewDelegate


    - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
        [self.searchedBar resignFirstResponder];
    }

    - (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar {
        [self.searchedBar resignFirstResponder];
        [self queryForTable];
        [self loadObjects];

    }







    @end

Update image of UIImageView in NSmutableArray?

I have:

Class Piece inherit UIImageView;

- (void)setJumpAt:(int)frame {
NSMutableArray *ret = [SkinConstants BallSelected];
NSString *name = [NSString stringWithFormat:@"balls-%d-%d", color - 1, [[ret objectAtIndex:frame] intValue]];
UIImage *a = [UIImage imageNamed:name];
NSLog(@"%d setJumpAt: %@", self.tag ,name);
[self performSelectorOnMainThread:@selector(setImage:) withObject:a waitUntilDone:NO];
[self  setNeedsDisplay];
[self setNeedsLayout];}

Class Player contain NSMutableArray of Piece;

Class JumpThread contain NSTimer use to set image of Piece;

- (void) timer_Tick{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
        [piece setJumpAt:frame++];
        [piece setNeedsDisplay];
        if (frame == len)
            frame = 0;
    dispatch_async(dispatch_get_main_queue(), ^{
    });
});}

I run code normal, but image of Piece not change in mainview, Sorry, I'm not so good at English.

Create a Url shortcut in Xcode using Objective c

In my app users can upload images to my website and they can share the link. What I need to do is to create a link shortcut.

For example I have this link: (http://ift.tt/1dpVk0W)

i need to change the link to (for example): wedv.ghfi

is it possible to do it?

Thanks

Can cocos-2dx play a song from the phone's library?

I'm using an MPMusicPlayerController to access and play music in an objective C file, but I need to play it in my C++ file using SimpleAudioEngine. Is it possible to select an item with MPMusicPlayerController and use its URL(ipod-library://item/item.m4a?id=456458322781804615) to play the music?

Deterministic shuffle in Objective C

This code in Java is the implementation of Knuth's shuffle, but a deterministic one, controllable by the seed to the random number generator.

public String shuffleString(String data, long shuffleSeed) {
    if(shuffleSeed!=0) {
        Random rnd = new Random(shuffleSeed);
        StringBuilder sb = new StringBuilder(data);
        int n = data.length();
        while(n>1) {
            int k = rnd.nextInt(n--);
            char t = sb.charAt(n);
            sb.setCharAt(n, sb.charAt(k));
            sb.setCharAt(k, t);
        }
        return sb.toString();
    }
    else {
        return data;
    }
}

How can I implement a deterministic shuffle in Objective C that outputs the same shuffle order given the same seed? I am using srandom(_shuffleSeed); and random()%(n--) knowing that arc4_random is better but that cannot be seeded.

- (NSString*) shuffleString:(NSString*) data withShuffleSeed:(int) shuffleSeed {
    if(shuffleSeed!=0) {
        srandom(_shuffleSeed);
        NSMutableString *result = [[NSMutableString alloc] initWithString:data];
        unsigned long n = data.length;
        while(n>1) {
            unsigned long k = random()%(n--);
            unichar t = [result characterAtIndex:n];
            NSRange r1 = {n,1};
            [result replaceCharactersInRange:r1 withString:[NSString stringWithFormat:@"%c", [result characterAtIndex:k]]];
            NSRange r2 = {k,1};
            [result replaceCharactersInRange:r2 withString:[NSString stringWithFormat:@"%c", t]];
        }
        return result;
    }
    else {
        return data;
    }
}

Currently, the two shuffle methods do not generate the same result for the same input parameters. I am sure I am missing something!