mardi 4 août 2015

Modal view doesn't respect Size Classes

I have two view controllers, each one loading their view from their own .xib file. I'm using size classes to display a different layout based on whether the device is in portrait and landscape mode.

The first view works fine: I can change orientations and the view is updated as in the size classes. However the second view doesn't work properly. If I present it while in portrait mode, changing to landscape doesn't update the view the way it should. However presenting it while in landscape mode works fine, and I can rotate back to portrait without issues.

I haven't done anything differently in the two .nib's, and I simply can't figure out why it's not working properly.

Have anyone experienced the same issue before, and know how I would go about fixing it?



via Chebli Mohamed

If-statement won't check NSArray

I am trying to create an if statement that checks to see if the selected cell is equal to an object in an array and if it is then it will set an NSURL accordingly. The table that I am referencing is from another view controller called PopOverViewController that I have created a delegate and used in the destinationViewController.

ViewController.m:

-(void) didLoadSelectedLayer:(NSString *)selectedLayer{
self.popOverArray = [[NSArray alloc] initWithObjects:@"Electric Radio", @"Electric Truck", @"Gas Radio", @"Gas Truck", @"Meter", @"Sewer Radio", @"Sewer Truck", @"Support Radio", @"Support Truck", @"Water Radio", @"Water Truck", @"Select All", nil];

if ([_popoverTableVC.myTable.indexPathForSelectedRow isEqual:@"Electric Radio"]) {
    _url = [NSURL URLWithString:@"http://somewebsite.com"];
}else{

}

I originally had a switch statement but since switch statements cannot use NSStrings I am confused on how to achieve the desired effect.

This is the PopOverViewController.h where I create the delegate:

#import <UIKit/UIKit.h>
#import <ArcGIS/ArcGIS.h>

#pragma mark - popoverTableViewControllerDelegate

@protocol popOverTableViewControllerDelegate <NSObject>
@required
-(void) didLoadSelectedLayer:(NSString *)selectedLayer;


@end

@interface PopOverTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
{
AGSFeatureLayer *popOverLayer;

IBOutlet UITableView *myTable;


}
@property (nonatomic, strong)IBOutlet UITableView *myTable;
@property (nonatomic, strong) NSArray *popOverArray;
@property (nonatomic,strong) id<popOverTableViewControllerDelegate> delegate;
//-(void)didSelectObject:(UITableView *)tableView :(NSInteger *)key;
@end

This is the PopOverViewController.m:

#import "PopOverTableViewController.h"
#import "ViewController.h"

#pragma mark - PopOverTableViewControler

@interface PopOverTableViewController ()
{
    NSURL *_url;
    ViewController *_ViewController;
}

@end

@implementation PopOverTableViewController
@synthesize delegate;

-(void)viewDidLoad
{
    [super viewDidLoad];
    self.popOverArray = [[NSArray alloc] initWithObjects:@"Electric Radio", @"Electric Truck", @"Gas Radio", @"Gas Truck", @"Meter", @"Sewer Radio", @"Sewer Truck", @"Support Radio", @"Support Truck", @"Water Radio", @"Water Truck", @"Select All", nil];
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return [self.popOverArray count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
        NSString *selectedLayer = [_popOverArray objectAtIndex: indexPath.row];
        [self.delegate didLoadSelectedLayer:selectedLayer];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier =@"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.textLabel.text = [self.popOverArray objectAtIndex:indexPath.row];
    return cell;
}


@end



via Chebli Mohamed

Transfering code from cellForItemAtIndexPath to a CollectionViewCell (Parse Back-End)

I'm using Parse as the database for my app. I want to create a CollectionViewCell and transfer my code there, instead of having it inside the View Controller's cellForItemAtIndexPath. How do I do this?

Thanks.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"productCell";

    ProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    PFObject *product = [self.products objectAtIndex:indexPath.row];

    NSString *price = [NSString stringWithFormat:@"$%@.00", product[@"price"]];

    cell.price.text = price;

    PFFile *userImageFile = product[@"firstThumbnailFile"];
    [userImageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
        if (!error) {
            UIImage *thumbnailImage = [UIImage imageWithData:imageData];
            UIImageView *thumbnailImageView = [[UIImageView alloc] initWithImage:thumbnailImage];

            cell.image.image = thumbnailImageView.image;
        }
    }];

    return cell;
}

Cell.h

@interface ProductCell : UICollectionViewCell

@property (nonatomic, weak) IBOutlet UIImageView *image;
@property (nonatomic, weak) IBOutlet UILabel *price;

@end



via Chebli Mohamed

how to send array value to another class

I have problem with send array value to another class. I'm sure that it's obvious but I don't have any idea to do this.

I'll be glad for any example code.

Problem: class1 send text from searchBar to class2. In class2 I get a data from www[JSONModel] and generate an array. My problem is how to send value this array to class1 and make reloadData in tableView.

To send data from class1 to class2 I use delegate method [SearchTextDelegate] I tried to make next delegate to send data from class2 to class1 but it doesn't work.

Thanks in advance.

my class1.m:

#pragma mark - searchBar
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {

    self.mySearchText = [NSString stringWithFormat:@"%@", text];
    NSLog(@"mySearchText: %@", self.mySearchText);

    if (text != 0) {

        APIClient *wskAPI = [[APIClient alloc]init];
        wskAPI.delegate = self;
        wskAPI.searchText = self.mySearchText;
        [wskAPI createSearchString];
    }
    [self.tableView reloadData];
}

#pragma mark - Sample protocol delegate
-(void)searchProcessCompleted {

    [self.tableView reloadData];
}

my class2.h [APIClient.h]:

#import <Foundation/Foundation.h>
#import "ITunesResultModel.h"

@protocol SearchTextDelegate <NSObject>

-(void)searchProcessCompleted;

@end

@interface APIClient : NSObject

@property (strong, nonatomic) id delegate;
@property (assign) id <SearchTextDelegate> stringDelegate;

@property (strong, nonatomic) NSString *searchString;
@property (strong, nonatomic) NSString *searchText;

@property (strong, nonatomic) ITunesResultModel *iTunesModel;
@property (strong, nonatomic) NSArray *resultArray;

-(void)createSearchString;

@end

my class2.m [APIClient.m]:

#import "APIClient.h"
#import "ITunesResultModel.h"
#import "JSONModelLib.h"
#import "class1.h"

@implementation APIClient

static NSString * const ITunesOnlineURLString = @"http://ift.tt/1CToUkG";

-(void)createSearchString {

    NSLog(@"searchTextAPI: %@", self.searchText);

    self.searchString = [NSString stringWithFormat:@"http://ift.tt/1j7O455", self.searchText];

    //fetch the feed
    self.iTunesModel = [[ITunesResultModel alloc] initFromURLWithString:self.searchString
                                         completion:^(JSONModel *model, JSONModelError *err) {

                                             //json fetched
                                             //NSLog(@"result: %@", self.iTunesModel.results);

                                         }];  
}

@end



via Chebli Mohamed

Swift ios is it bad to have an embedded table view

I wonder if there is any downside in having an embedded table view?

I have a navigation controller VC that leads to another VC which is my apps "main/root" VC.

Inside that VC I have a container view which holds an table view.

Is this a bad setup? The table view then has more segues leading to other VC's



via Chebli Mohamed

Three-Finger UIPanGestureRecognizer doesn't work when Accessibility -> Zoom is on in "Settings App"

So, I have this code which basically creates a UIPanGestureRecognizer and adds it to the view. In the target method I am just printing the number of touches. It works fine under normal circumstance; and print correct number of touches.

But if "Settings -> Accessibility -> Zoom" is turned On, then it fails for 3-finger touch.

- (void)viewDidLoad
{
  [super viewDidLoad];
  UIPanGestureRecognizer *tempGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleTempGesture:)];
  tempGesture.minimumNumberOfTouches = 1;
  tempGesture.maximumNumberOfTouches = 3;
  [tempGesture setDelegate:self];
  [self.view addGestureRecognizer:tempGesture];
}

- (void)handleTempGesture:(UIGestureRecognizer *)recognizer
{
  NSUInteger touches = recognizer.numberOfTouches;
  NSLog(@"Touches Count: %i", (int)touches);
}

Is there a way around it i.e. without having to turn off the zoom.

PS: Even 3-Finger UITapGestureRecognizer doesn't work.



via Chebli Mohamed

iOS: CoreLocation Speed and Heading not working on physical device

I have some code that works 100% fine in the simulator. It shows heading and speed 100% correct; however; the second I run it on a proper device the speed and heading results are -1.

Anybody any ideas as to why? Or how to try and troubleshoot this problem?



via Chebli Mohamed

Change page in PageViewController from a page inside the controller?

I have a UIPageViewController that has 3 pages. How can I switch to a page that is within the UIPageViewController on a button tap? (Each of the pages are a separate UIViewController that I made in the storyboard).

I've tried a lot of code but I keep getting errors as I made my UIPageViewController inside my storyboard and I set it up like this:

PageViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.dataSource = self;
    self.navigationController.navigationBarHidden = NO;

    [self setViewControllers:@[[self.storyboard instantiateViewControllerWithIdentifier:@"Main"]] 
                   direction:UIPageViewControllerNavigationDirectionForward 
                    animated:YES
                  completion:nil];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    if ([viewController isKindOfClass:[NavView2ViewController class]])
       return nil;

    return [self.storyboard instantiateViewControllerWithIdentifier:@"two"];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
    if ([viewController isKindOfClass:[NavViewController class]])
        return nil;

    return [self.storyboard instantiateViewControllerWithIdentifier:@"one"];
}



via Chebli Mohamed

Is anybody else seeing duplicate calls to handleActionWithIdentifier:forLocalNotification: in WatchKit?

I am getting some very strange behavior with my WatchKit handling of local notification actions that I'm pretty sure is a system bug. I'm wondering if anybody else is seeing the same thing.

(This is using iOS 8.4 and WatchKit 2.0, with an Objective-C app build with Xcode 6.4)

It's too much code to post, and the code is property of the client, so I'll have to describe it.

The background:

I am adding custom "long look" notification support to a client's app.

The app creates geofences around vendor locations. When the user enters one of the geofences, the location manager send a didEnterRegion message to my class that handles geofences.

I turn around and generate a local notification of a defined category. That category is defined as having 2 different UIMutableUserNotificationActions attached to it, one for showing more info about the vendor, and one for displaying driving directions to that vendor's location. (We won't talk about the fact that the user is in shouting distance of the vendor when the geofence fires, so they can SEE the vendor's shop. This is what the client wants, and he's paying me to do it this way.)

The local notification is set to fire immediately (or for testing, I create notifications set to fire in a few seconds.)

The system can do one of 3 things when the notification fires.

1. If the app is running in the foreground, it will send the app delegate a `application:didReceiveLocalNotification:` message.
2. If phone is awake but the app is in the background, it displays the local notification with a system banner/alert (depending on the user's settings.) That banner/alert has buttons for my 2 actions.
3. If the phone is locked and the user has a paired Apple Watch that is allowed to receive notifications, the local notification is sent to the watch.

The Apple Watch app has a custom subclass of WKUserNotificationInterfaceController that is set up to handle this category of user notifications. It adds an image, a title, and a message body to a custom interface controller, with data it gets from the the userInfo dictionary attached to the local notification.

If the user taps one of the action buttons on the WKUserNotificationInterfaceController ("more info" or "directions"), the watch's main interface controller gets a handleActionWithIdentifier:forLocalNotification: message. The code is set up to then send an `openParentApplication:reply:error:' message to the iPhone app. It passes along the user info dictionary it received in the local notification.

The iPhone app responds to the openParentApplication:reply:error message by either requesting driving directions from the location manager (which launches the maps app) or displaying the appropriate info page from the app for the specified vendor.

If the phone is locked when the watch sends the `openParentApplication:reply:error: message to the iPhone, the user doesn't get any feedback, since the phone is locked and Apple doesn't allow a phone to wake itself up.

In that case I therefore invoke the reply block with a dictionary entry of @{@inBackGround: @(YES)}. The watch's reply block checks for inBackground==YES, and if it is, it displays a message to the user that they nee to open the iPhone app in order to see the info/directions.

The problem:

If I launch the iPhone app and trigger a local notification when the phone is locked the first time, the message goes to the watch, the watch displays my custom long look with "more info" and "directions" buttons, and tapping one of the action buttons invokes the watch's handleActionWithIdentifier:forLocalNotification: method, as expected. The watch's handleActionWithIdentifier:forLocalNotification: method sends an openParentApplication:reply:error message to the phone, and the phone displays the appropriate response to the user when the user goes back to the app.

However, the problem comes in if I then trigger a new local notification (also with the phone locked) for a different vendor, with different GPS coordinates and userInfo that points to a different screen of information to display on the phone. When my watch buzzes and I raise it to my wrist, as the "long look" notification for the new local notification is displayed, the watch's handleActionWithIdentifier:forLocalNotification: method fires again, with the identifier and userInfo dictionary from the previous local notification. (I haven't tapped any action buttons on this new notification, or responded to a local notification message on the phone.)

Then, if the user clicks the "more info" action button on the watch's new long look notification controller, that action fires.

The result of this is that when the user goes to his phone, he sees the information for the new vendor he asked about, but when he clicks that away, there is a duplicate copy of the info for the first vendor on his screen.

I've debugged this very carefully, and confirmed that the watch app's interface controller's handleActionWithIdentifier:forLocalNotification: method is being called spuriously. I added a unique NSDate timestamp to the userInfo in the local notification that the iPhone posts, and I see that exact same timestamp repeated in the second (spurious) invocation of the first handleActionWithIdentifier:forLocalNotification: when the second long look notification is displayed.

Has anybody else run across this problem? I guess it's time to file a Radar bug, but I'm not sure what set of steps from my client's app triggers the problem, and it might take me a full day or more to work out a minimum demo app to demonstrate the problem. I know from experience that Apple won't pay any attention to my bug report unless I give them an app that lets them create a repeatable fail-case, along with painfully detailed instructions on how to use it.

The fix:

The fix I have come up with is a dreadful hack. On the phone, I embed a unique "actionFireDate" NSDate into the userInfo dictionary for the local notification. On the watch, I create an empty NSMutableSet "actionFireDates" at startup. When I get a handleActionWithIdentifier:forLocalNotification: call, I get the userInfo for the local notification, get the timestamp NSDate I put in the userInfo dictionary, and check to see if that unique NSDate is in my "actionFireDates" set. If it is, I simply ignore the action. If it's not, I add the new NSDate from the userInfo dictionary in to my set of action fire dates.



via Chebli Mohamed

How to setup accessibility for all table cell contents in iOS?

I setup the accessibility for the table cell successfully. But I have two cases:

If I set the accessibility to self.containerview, I need to tap on each element and it gives the voice over for each element.

If I set the accessibility to self, the voice over is reading the cell content except the image view. Somehow, the voiceover is neglecting the image view and is only reading the uilabels.

This is how I setup the accessibility:

-(void)awakeFromNib{
 [UIViewController makeStaticViewAccessible:self]; //tried self.containerView, If i put self here, voice over is not reading the imageview
 }

and the method:

 +(void)makeStaticViewAccessible:(UIView *)view {
for(UIView *subview in [view subviews]){
     if([subview isMemberOfClass:[UIView class]]){
        [self makeStaticViewAccessible:subview];
    }else if([subview isMemberOfClass:[UILabel class]]){
        [subview setIsAccessibilityElement:YES];
        [subview setAccessibilityTraits:UIAccessibilityTraitStaticText];
    } else if([subview isMemberOfClass:[UIButton class]]){
        [subview setIsAccessibilityElement:YES];
        [subview setAccessibilityTraits:UIAccessibilityTraitButton];
    } else if([subview isMemberOfClass:[UIImageView class]]){
        [subview setIsAccessibilityElement:YES];
        [subview setAccessibilityTraits:UIAccessibilityTraitImage];
    } else if([subview isMemberOfClass:[UITextField class]]){
        [subview setIsAccessibilityElement:YES];
        [subview setAccessibilityTraits:UIAccessibilityTraitSearchField];
    }
}

}



via Chebli Mohamed

Notification throws exception

It did work as it should in my previous project but all of a sudden it throws exception and I've compared two, can't really figure out because both situations are identical.

This is what I'm getting -

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UISwipeGestureRecognizer toggleMenu:]: unrecognized selector sent to instance 0x7fb663f3cda0'

In OptionView.m

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toggleMenu:) name:@"toggleMenuYes" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toggleMenu:) name:@"toggleMenuNo" object:nil];

-(void)toggleMenu:(NSNotification *)shouldOpenMenu{
[self.animator removeAllBehaviors];

NSString *one = @"1";

if (shouldOpenMenu.object == one) {
    NSLog(@"yes");
    self.yesOrNo = YES;  
}
else {
    self.yesOrNo = NO;  
}   

}

In myVC.m

UISwipeGestureRecognizer *showMenuGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self
                                                                                          action:@selector(handleGesture:)];
    showMenuGesture.direction = UISwipeGestureRecognizerDirectionRight;
    [self.optionViewCell addGestureRecognizer:showMenuGesture];
    showMenuGesture.delegate = self;


    UISwipeGestureRecognizer *hideMenuGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self
                                                                                          action:@selector(handleGesture:)];
    hideMenuGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.optionViewCell addGestureRecognizer:hideMenuGesture];
    hideMenuGesture.delegate = self;


-(void)handleGesture:(UISwipeGestureRecognizer *)gesture{

if (gesture.direction == UISwipeGestureRecognizerDirectionRight) {

    [[NSNotificationCenter defaultCenter] postNotificationName:@"toggleMenuYes" object:@"1"];
}
else{

    [[NSNotificationCenter defaultCenter] postNotificationName:@"toggleMenuNo" object:@"0"];
}

}



via Chebli Mohamed

AFNetworking 2.0 POST issue | replacing deprecated multipartFormRequestWithMethod:path:parameters

I am migrating an iOS app from Xcode4 to Xcode7 (beta 4). Dependency to AFNetworking is automatically resolved via Pods. AFNetworking 2.0 is not backwards compatible with AFNetworking 1.0 so I modified part of the source. Here is

  • File structure
  • Log and
  • the related Source code

Issue below

/Api/ApiClient.m::: error: unexpected interface name 'NSData': expected expression
                NSData* callerData = [@"http://nikyotis.xyz" dataUsingEncoding:NSUTF8StringEncoding];
                ^

/Api/ApiClient.m::: error: use of undeclared identifier 'callerData'
                NSData* callerData = [@"http://nikyotis.xyz" dataUsingEncoding:NSUTF8StringEncoding];

at line 280 of the example above

enter image description here

Substituting NSData with NSString results in the error below

enter image description here

Original AFNetwork-1.0 code below

enter image description here

I try to migrate to AFNetwork-2.0 by replacing the routine with either //1

enter image description here

or //2

enter image description here

without any success



via Chebli Mohamed

Core Data Model Url is Nil in Framework

I am using Apple Documented Code to link up CoreData xcdatamodeld file but it works brilliantly in the project but fails in Framework. Here is the code I am using to create the managedObjectModel. I get nil modelURL in case of Framework.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths lastObject];

    self.persistantStorePath = [documentDirectory stringByAppendingString:[NSString stringWithFormat:@"/%@.sqlite",name]];
    NSURL *storeURL = [NSURL fileURLWithPath:self.persistantStorePath];
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:name withExtension:@"momd"];

    self.managedObjectContext = [[NSManagedObjectContext alloc] init];
    self.managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

Also, I tried [NSManagedObjectModel mergedModelFromBundles:nil] and the surprising point is, it works too.

I don't know why the Apple Documentation fails in case of Framework



via Chebli Mohamed

RestKit: Values to BOOL

I have an NS_ENUM that holds the status of a checklist. The two properties are Pending and Completed.

typedef NS_ENUM (NSUInteger, ChecklistStatus) { Pending, Completed };

I am trying to take the status and map that to a true/false value. The method i'm doing this with is via RKValueTransformer.

Here is the code for that:

+(RKValueTransformer *)checklistStatusToBooleanTransformer
{
    RKValueTransformer *transformer = [RKBlockValueTransformer valueTransformerWithValidationBlock:^BOOL(__unsafe_unretained Class sourceClass, __unsafe_unretained Class destinationClass) {
        return ([sourceClass isSubclassOfClass:[NSNumber class]]);
    } transformationBlock:^BOOL(NSNumber *inputValue, __autoreleasing id *outputValue, __unsafe_unretained Class outputClass, NSError *__autoreleasing *error) {
        // validate the input
        RKValueTransformerTestInputValueIsKindOfClass(inputValue, [NSNumber class], error);
        if([inputValue isEqual:@(Completed)]) {
            *outputValue = [NSNumber numberWithBool:YES];
        } else {
            *outputValue = [NSNumber numberWithBool:YES];
        }

        return YES;
    }];

    return transformer;
}

I'm not able to explicitly cast my output value as a BOOL, so i'm really lost as to what I should do here.

Any help would be greatly appreciated!



via Chebli Mohamed

How to convert c program to fully portable for ios

I wrote a simple c program for connect to ldap server using opelLdap c library. now I want to run that c program on ios device. but when I move that c program to xcode project it says ldap.h is missing. ldap.h file is saved in standard include file location so it include this way #include <ldap.h> but I move this file to my xcode project and include it this way #include "ldap.h" it generate so many error because this ldap.h header file contain lot of other standard header files and they have their own dependencies and so on. they all are include this way #include <header.h> it is not possible to convert all the <> to " " one by one. is there any way to to this thing. actually I need to move my code with it's all dependencies I am new to both of this c and xcode(swift/objective-c)



via Chebli Mohamed

modal segue to a xib from a xib?

I have an app that doesn't use storyboards. I use only Xibs.

Repeat: I AM NOT USING STORYBOARDS. Apologies if you've found this to be a duplicate, but I have only found questions solutions related to storyboards or people attempting to transition from a storyboard to a xib.

I have created a prompt xib that I would like to present modally from a table view controller xib (named TVC.xib) with their respective .h/.m view controller files. The TVC is nested in a navigation controller.

I can get the prompt to present itself, but I want it to present itself modally. Unfortunately, the presentModalViewController has been deprecated. What is the current option to present a view controller modally in code?

Here is my code: (in the TVC.m)

PromptViewController *promptVC = [[PromptViewController alloc] initWithNibName:@"PromptXib" bundle:nil];
UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:promptVC];
[self.navigationController presentViewController:navVC animated:YES completion:^{
    NSLog(@"presented prompt vc");
}];

Ideally I could replace the method in the 3rd line with self.navigationController presentMODALViewController... etc, but it's deprecated.

How do I present a xib modally from a xib?



via Chebli Mohamed

Dismiss keyboard when touching outside of UITextField in iwatch

I know that I need to tell my UITextField to resign first responder when I want to dismiss the keyboard, but I'm not sure how to know when the user has pressed the out side of view?



via Chebli Mohamed

Nesting NSDictionary based on value

i've data from Library that return this:

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:idChallengerN,@"idChallenger",dateFrom, @"date", nil];

[_array addObject:dict];

If i print _array this is there result:

_array = (
{
date = "2015-07-31 14:50:40 +0000";
idChallenger = 43;
},
{
date = "2015-07-31 19:30:00 +0000";
idChallenger = 22;
}
)

and it's ok, now I should get each 'date' and group this _array based on weeks...

I've tried:

NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];   

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

    NSDictionary *dict = [_array objectAtIndex:i];

    NSDate *date = [dict objectForKey:@"date"];

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponents = [calendar components:NSWeekOfYearCalendarUnit fromDate:date];

    NSLog(@"date week = %ld",(long)[dateComponents weekOfYear]);

    NSNumber *weekN = [NSNumber numberWithInteger:[dateComponents weekOfYear]];

    if ([tempDic objectForKey:weekN]) {

       //contains
    }
    else{

      //not contains
    }

weekN return the number of the week in year based on 'date',

now i'm stuck to how group certain data if have the same number of week, like this for example:

weekN = 31 {
  {
  idChallenger = 43;
  idChallenger = 22;
  }
}
weekN = 32 {
  {
  idChallenger = 55;
  idChallenger = 21;
  idChallenger = 678;
  }
}



via Chebli Mohamed

UIPopoverPresentationController Arrow not pointing to Rect

I'm trying to implement a UIPopoverPresentationController and I'm running into this problem where the arrow doesn't point to the sourceRect when it's near the screen's bounds. How can I configure this so the arrow points to the rect instead of above it?

For example:

enter image description here

Thanks!

EDIT: Sorry for lack of information. I'm working on iOS 8 and testing on iPhone 6 as of right now.

In the picture above, I had attached a white colored UIView to see what the sourceRect looked like on the screen.

The code I'm using:

    // contentView is custom UIViewController
    contentView.preferredContentSize = CGSizeMake(250, 100);

    contentView.modalPresentationStyle = UIModalPresentationPopover;
    UIPopoverPresentationController *popover = contentView.popoverPresentationController;
    popover.delegate = self;
    popover.permittedArrowDirections = UIPopoverArrowDirectionLeft;
    popover.sourceView = self.imageView;
    popover.sourceRect = CGRectMake(78, 28, 95, 5);
    [self presentViewController:contentView animated:YES completion:nil];



via Chebli Mohamed

UICollectionView and AutoLayout

I'm trying to create a UICollectionView whose width/height and coordinates are defined using AutoLayout (using SnapKit). When using the default UICollectionView constructor it fails with the following reason:

reason: 'UICollectionView must be initialized with a non-nil layout parameter'

The only constructor that allows a layout to be passed in, also requires a frame, so I tried using CGRectZero as the value for the frame like so:

collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)

I then used SnapKit to setup the constraints like so:

collectionView?.snp_makeConstraints { make -> Void in
        make.width.equalTo(view)
        make.height.equalTo(300)
        make.top.equalTo(someOtherView)
    }

However, when doing so the UICollectionView is never rendered. In fact, I do not see the data source being called at all.

Any thoughts on how to use AutoLayout with a UICollectionView or what I might be doing wrong?



via Chebli Mohamed

QR Code to read faster?

Here is my code for my QR Code Reader. What I need to accomplish is matching the QR Code to the one I have created. This code works, except it takes at least 30 seconds to verify that it has matched my QR Code. How can I make it faster??

//  QRCodeVC.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>


@interface QRCodeVC : UIViewController <AVCaptureMetadataOutputObjectsDelegate> {

NSTimer *timer;
}

@property (weak, nonatomic) IBOutlet UIView *viewPreview;
@property (strong, nonatomic) IBOutlet UIImageView *imageCheckmark;
@property (strong, nonatomic) IBOutlet UILabel *wrongQRCodeLabel;
@property(nonatomic, assign) NSString *messageString;

@end



//  QRCodeVC.m

#import "QRCodeVC.h"
#import <Parse/Parse.h>

@interface QRCodeVC ()

@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@property (nonatomic) BOOL isReading;

-(BOOL)startReading;
-(void)stopReading;
-(void)loadBeepSound;

@end

@implementation QRCodeVC

- (void)viewDidLoad {
[super viewDidLoad];

timer = [NSTimer scheduledTimerWithTimeInterval:(1.0/2.0) target:self selector:@selector(loading) userInfo:nil repeats:YES];


if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

self.imageCheckmark.image = [UIImage imageNamed:@""];

// Initially make the captureSession object nil.
_captureSession = nil;

// Set the initial value of the flag to NO.
_isReading = NO;

// Begin loading the sound effect so to have it ready for playback when it's needed.
[self loadBeepSound];

self.viewPreview.layer.cornerRadius = 20;
self.viewPreview.layer.masksToBounds = YES;
}

- (void) viewWillAppear:(BOOL)animated {


[self.navigationController.navigationBar setHidden:NO];

// Navigation Bar Attibutes
self.navigationController.navigationBar.barTintColor = [UIColor redColor];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
[self.navigationController.navigationBar
 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
self.navigationController.navigationBar.translucent = NO;


if (!_isReading) {
    // This is the case where the app should read a QR code when the start button is tapped.
    if ([self startReading]) {

    }
}
else{
    // In this case the app is currently reading a QR code and it should stop doing so.
    [self stopReading];
}

// Set to the flag the exact opposite value of the one that currently has.
_isReading = !_isReading;
}

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


#pragma mark - Private method implementation

- (BOOL)startReading {
NSError *error;

// Get an instance of the AVCaptureDevice class to initialize a device object and provide the video
// as the media type parameter.
AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

// Get an instance of the AVCaptureDeviceInput class using the previous device object.
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];

if (!input) {
    // If any error occurs, simply log the description of it and don't continue any more.
    NSLog(@"%@", [error localizedDescription]);
    return NO;
}

// Initialize the captureSession object.
_captureSession = [[AVCaptureSession alloc] init];
// Set the input device on the capture session.
[_captureSession addInput:input];


// Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session.
AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
[_captureSession addOutput:captureMetadataOutput];

// Create a new serial dispatch queue.
dispatch_queue_t dispatchQueue;
dispatchQueue = dispatch_queue_create("myQueue", NULL);
[captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
[captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];

// Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
_videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
[_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
[_viewPreview.layer addSublayer:_videoPreviewLayer];


self.messageString = AVMetadataObjectTypeQRCode;

// Start video capture.
[_captureSession startRunning];

return YES;
}


-(void)stopReading{

//    self.imageCheckmark.image = [UIImage imageNamed:@"checkmark_RA"];

// Stop video capture and make the capture session object nil.
[_captureSession stopRunning];
_captureSession = nil;

/*
 // Remove the video preview layer from the viewPreview view's layer.
 [_videoPreviewLayer removeFromSuperlayer];
 */
}


-(void)loadBeepSound{
// Get the path to the beep.mp3 file and convert it to a NSURL object.
NSString *beepFilePath = [[NSBundle mainBundle] pathForResource:@"beep" ofType:@"mp3"];
NSURL *beepURL = [NSURL URLWithString:beepFilePath];

NSError *error;

// Initialize the audio player object using the NSURL object previously set.
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:beepURL error:&error];
if (error) {
    // If the audio player cannot be initialized then log a message.
    NSLog(@"Could not play beep file.");
    NSLog(@"%@", [error localizedDescription]);
}
else{
    // If the audio player was successfully initialized then load it in memory.
    [_audioPlayer prepareToPlay];
}
}


#pragma mark - AVCaptureMetadataOutputObjectsDelegate method implementation

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {

// Check if the metadataObjects array is not nil and it contains at least one object.
if (metadataObjects != nil && [metadataObjects count] > 0) {
    // Get the metadata object.
    AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
    if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {

        NSString *scanResult = [metadataObj stringValue];

        if ([scanResult isEqualToString:@"MAILTO:capeupdev@gmail.com"]) {

            self.imageCheckmark.image = [UIImage imageNamed:@"checkmark_RA"];


            [[PFUser currentUser] incrementKey:@"Points" byAmount:[NSNumber numberWithInt:1]];
            [[PFUser currentUser] saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    NSLog(@"The object has been saved.");
                } else {
                    NSLog(@"There was a problem");
                }
            }];


            //if statement for 12 hour count. Maybe if (timer < 43,000 || NSDate 12 hours) {
            // }

            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Congratulations!" message:@"1 point has been added to your account" delegate:nil cancelButtonTitle:@"Yes!" otherButtonTitles:nil];

            [alertView show];

            NSLog(@"Correct QR Code!");

        } else {

            self.wrongQRCodeLabel.text = @"Wrong QR Code!";
            NSLog(@"Wrong QR Code!");

        }

        NSLog(@"%@", scanResult);

        // If the found metadata is equal to the QR code metadata then update the status label's text,
        // stop reading and change the bar button item's title and the flag's value.
        // Everything is done on the main thread

        [self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];

        _isReading = NO;

        // If the audio player is not nil, then play the sound effect.
        if (_audioPlayer) {
            [_audioPlayer play];
        }
    }
}


}

- (void) loading {

}

//if (metadataObjects != nil && metadataObjects.count > 0) {
//    AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects firstObject];
//    if ([[metadataObject type] isEqualToString:AVMetadataObjectTypeQRCode]) {
//        NSString * scanResult = [metadataObject stringValue];
//        NSLog(@"%@",scanResult);

 /*
NSNumber *currentPoints = [PFUser currentUser][@"Points"];
int difference = currentPoints.intValue - 10;

if (difference < 0) {

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"You don't have 10 Points" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

[alertView show];
}
*/

@end



via Chebli Mohamed

iOS best practice to display errors for a uitableview after pull to refresh and/or scroll to load more

I've recently developed an android app and used toasts to display any errors (network or web service errors) that may have happened when pulling to refresh or scrolling to load more in a table. They were great at displaying these errors without being to invasive or requiring user input to remove.

Seeing as iOS doesn't have a toast equivalent I wanted to know what are considered best practices on iOS to display errors when pulling to refresh or scrolling to load more in a UITableView.

Personally a UIAlertView seems a bit to invasive and requires a user input to remove, but I could be wrong and that may be the standard on iOS. I'm not opposed to using libraries out there that have implemented toast like views, but I figured I'd check if there was a better way since it's not built in.

Any suggestions on this would be great. Thanks!



via Chebli Mohamed

Changing mutable class into immutable

I'm facing an architecture decision which I need some help.

I'm creating a library that will be used by several clients. In this library I have a class named LibClass with a read-write property named aProperty and also class named LibManager which holds a reference to a Libclass instance. LibManager is responsible to update LibClass properties.

The clients can get the LibClass instance via a method on LibManager, let's call it getLibClassInstanceMethod.

I don't want my clients to have the ability to change aProperty in LibClass as this means that the clients can change my library model. I only want LibManager to have access changing aProperty.

I've been contemplating with several solutions:

option 1

inside getLibClassInstanceMethod return deep copy of the object.

Pros: I'm always sure that only the library has full access to the model.

Cons: Memory consumption - each time I want to get the object, I need to clone it.

option 2

Making the LibClass immutable; Every time I want to make a change to the class properties, I need to create a new class and in the designated initializer(constructor) pass the new values and the destroy the old object.

Pros: I make the class become immutable which is exactly what I want

Cons: When classes become big it's a little weird to always re create classes just because one property changed.

option 3

Creating some sort of mutable/immutable pair like NSString/NSMutableString.

Pros: Not sure

Cons: For each class there's need to be two counterparts which double the number of classes.

I'm really not sure which path to go. What would you do?

Thanks



via Chebli Mohamed

How to sign out with Google+ on iPhone

I am writing an application where user can login using Google+. I followed GOOGLE Developer console and successfully logged in and obtained the user profile information through Access_Token. and i want to login through web view, but how to make sign out after login?

My Webview method

-(void)addWebView
{

    NSString *url = [NSString stringWithFormat:@"http://ift.tt/Kyk9ty",client_id,callbakc,scope,visibleactions];

    self.webview = [[UIWebView alloc]init];
    self.webview.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    self.webview.delegate = self;
    [self.view addSubview:self.webview];
    [self.webview  loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];


}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
    //    [indicator startAnimating];
    if ([[[request URL] host] isEqualToString:@"localhost"]) {

        // Extract oauth_verifier from URL query
        NSString* verifier = nil;
        NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:@"&"];
        for (NSString* param in urlParams) {
            NSArray* keyValue = [param componentsSeparatedByString:@"="];
            NSString* key = [keyValue objectAtIndex:0];
            if ([key isEqualToString:@"code"]) {
                verifier = [keyValue objectAtIndex:1];
                NSLog(@"verifier %@",verifier);
                break;
            }
        }

        if (verifier) {
            NSString *data = [NSString stringWithFormat:@"code=%@&client_id=%@&client_secret=%@&redirect_uri=%@&grant_type=authorization_code", verifier,client_id,secret,callbakc];
            NSString *url = [NSString stringWithFormat:@"http://ift.tt/IlrJjr"];
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
            [request setHTTPMethod:@"POST"];
            [request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
            NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
            receivedData = [[NSMutableData alloc] init];

        } else {
            // ERROR!
        }

        [webView removeFromSuperview];

        return NO;
    }
    return YES;
}



via Chebli Mohamed

How i can play [UInt8] audio stream?

I am connected to the server via TCP / IP and receives [UInt8]. I know that it is the audio. How to play the stream on the iPhone?



via Chebli Mohamed

How to use indexPathForItemAtPoint in TableViewController?

I'm using PFQueryTableViewController and in my PFQTVC.m, I've implemented scrollViewDidScroll method so I can get the indexPath of the visible cell when scrolling.

However, I get NO VISIBLE INTERFACE FOR 'PFQTVC' DECLARES THE SELECTOR 'INDEXPATHFORITEMATPOINT'.

UITableViewDataSource and UITableViewDelegate have been added.

What to do?

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
NSLog(@"Did Scroll");

CGRect visibleRect = (CGRect){.origin = self.tableView.contentOffset, .size = self.view.bounds.size};
CGPoint visiblePoint = CGPointMake(CGRectGetMidX(visibleRect), CGRectGetMidY(visibleRect));
NSIndexPath *visibleIndexPath = [self indexPathForItemAtPoint:visiblePoint];

NSLog(@"visible Index Path : %@", visibleIndexPath);

}



via Chebli Mohamed

UILabel in UITableViewCell using Autolayout sizes correctly but only wraps on rotation

I use the programatic constraints from the WWDC '14 talk on UITableViews so that my app can support dynamic text and adjust the height of my table view cells automatically. But the wrapping only shows up if I rotate the device to landscape and back. The first picture below shows this: the initial view is wrong. The second shows what I expected, but I only get the correct behaviour after I rotate to landscape and back.

Notice that the size of the cells is correct: the auto layout system has figured out that I need two lines of space, and yet the text did not wrap.

I tried setting the line break mode - it sort of works (breaks at a character or word depending on the mode, but I don't see the rest of the string until I rotate).

The constraints for the label are identical to the ones in the WWDC '14 talk. I get not auto layout complaints. I have set number of rows of the UILabel to 0, set the row height to UITableViewAutomaticDimension and set the estimated row height.

Has anyone seen this before and fixed it? What have I done wrong?

enter image description here

Second picture: enter image description here



via Chebli Mohamed

hmac nsdictionary - express req.body

i am trying to do a generic - hmac verification with an iOS app and an express node.js app.

generating the hmac using given samples at: http://ift.tt/1P42qG1

having the following problem: subclassed AFHTTPRequestOperationManager to gain access to POST: i want to hmac the nsdictionary parameters.

so convert the nsdicionary to json - hmac it - and set hmac header in request. on the receiver side, i use crypto-js and express to access the req.body - and hmac the json object.

problem is! - thos keys are not in same oder, even if i force the sort on the keys in nsdictionary, the transoformed json does not come in the order way.

after hours of googling i accepted that json objects cannot be orderd, in an reliable way.

so what is the best-practice to hmac an nsdictionary, by ignoring the order? (i could hmac on only a few keys, but that would be way to less generic, mean adding a dictionary key would require code change in ios and express)

generating the hmac only based on the URI - works fine, but its a way to open :)

regards helmut



via Chebli Mohamed

Bridging objective-c library in swift project does not work

In my swift project in need to use snmp++ project ( http://ift.tt/1fyN2Ff ). The snmp++ project is written in c++ and then objective-c wrapper is created for functions.

The project generates libMobileSNMP_PP.a file which i include in my swift project and then create a bridging header and in the bridging header inport "XISMobile_SNMP_PP.h".

Also included .mm and .h files in the swift project as shown in the attached image example1

enter image description here

at compile it gives "could not reference bridging file in the app".

I refered link Can I mix Swift with C++? Like the Objective - C .mm files but still issue exist.

I even tried steps as given in example as shown http://ift.tt/1P42pSz but no success.

Please tell where i'm doing or missing any step.



via Chebli Mohamed

Can't display MBProgressHUD progress animation properly

I would like to display a hud while the content is loading (and show the progress), but unfortunately it doesn't work properly. The hud appears on the screen when statusUpdate is 0.100000, but the loading bar doesn't moves until statusUpdate is not 1.000000 and the page loading finished. (After the view loaded sucessfully it animates from 0-100%.) I would appreciate if somebody could show me what I'm doing wrong.

// ViewDidLoad    
[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.mode = MBProgressHUDModeDeterminateHorizontalBar;
    HUD.delegate = self;
    HUD.labelText = @"Uploading";

    [HUD show:YES];
    [self hud:self.webView.estimatedProgress];
    if ([keyPath isEqualToString:@"estimatedProgress"] && object == self.webView) {

  //   [self.progressView setAlpha:1.0f];

 //    [self.progressView setProgress:self.webView.estimatedProgress animated:YES];



        NSLog(@"%f", self.webView.estimatedProgress);

   }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];


          NSLog(@"%f", self.webView.estimatedProgress);
    }
}

- (void) hud: (double)statusUpdate  {

    NSLog(@"STATUS %f", statusUpdate);

    int myInt = (int)statusUpdate;

    HUD.progress = (float)myInt;

}



via Chebli Mohamed

Adding UIButton in each UICollectionViewCell in Scrolling Filmstrip within UITableView

First off, let me describe the scenario I've got so far. Here's the basic rundown of how my UICollectionView in Scrolling Filmstrip style within UITableView works:

  • Create a normal UITableView with a custom UITableViewCell
  • Create a custom UIView that will be added to the cell's contentView
  • The custom UIView will contain a UICollectionView
  • The custom UIView will be the datasource and delegate for the UICollectionView and manage the flow layout of the UICollectionView
  • Use a custom UICollectionViewCell to handle the collection view data
  • Use NSNotification to notify the master controller's UITableView when a collection view cell has been selected and load the detail view.

enter image description here

So far, I've been able to create those described above but as you can see in the picture I also want to add an UIButton in each UICollectionViewCell so that when I tap the UIButton its image will change to checked mark and data in that UICollectionViewCell will be saved into an array. At the end, when I tap the top-right triangle button it will push to another view with the array that saves selected data passed on.

Here're all the relevant classes that I've got:

UITableView

  • ViewController.h
  • ViewController.m

UIView

  • ContainerCellView.h
  • ContainerCellView.m

UICollectionViewCell

  • CollectionViewCell.h
  • CollectionViewCell.m

UITableViewCell

  • ContainerCell.h
  • ContainerCell.m

My question is that I can't get my UIButton at least to show up (for now) with this below code:

ContainerCellView.m

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionViewCell" forIndexPath:indexPath];
    NSDictionary *cellData = [self.collectionData objectAtIndex:[indexPath row]];

    ...

    //  >>> Select Button <<<

    UIButton *button = (UIButton *)[cell viewWithTag:200];
    [button setFrame:CGRectMake(0, 0, 50, 60)];
    [button setTitle:@"Button" forState:UIControlStateNormal];
    [cell.contentView addSubview:button]; //???

    //  >>> End Select Button <<<<

    ...

    return cell;
}

ContainerCell.m

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        _collectionView = [[NSBundle mainBundle] loadNibNamed:@"ContainerCellView" owner:self options:nil][0];
        _collectionView.frame = self.bounds;
        [self.contentView addSubview:_collectionView];
    }
    return self;
}

What have I done wrong and how should I do this better? If you need more info, you're more than welcome to request. Thanks in advance.



via Chebli Mohamed

Swift iOS static uitableviewheader

I wonder if its possible to add a static uitableviewheader? I want the header to look like an extension of the navigation bar. But I can't get it to work, my header keeps scrolling with the table view.



via Chebli Mohamed

UPageViewController doesn't release memory when page is flipped

I am working on an ebook project, I am using ARC as well, however, when I flip the page in simulator, my memory grows rapidly, by the time I finish flipping it is close to 200MB. It seems memory is not being released, but isn't that what ARC is for? I removed my NSTimer and delegates all together to see if that was the culprit but to no avail. It seems like I have a retain cycle somewhere and I can't seem to find it. I am not using blocks either... Any ideas?



via Chebli Mohamed

Obj-c NSTimer - Slower than expected

I have to do heavy operation every < 1s. I'm using NSTimer, but its not that accurate as i expected... I'm using 2 timers. One to update data in my model and 2nd to update my views (few labels and custom 'fancy-circle' progress bar)

Ok... my code:

_valueTimer = 
  [NSTimer scheduledTimerWithTimeInterval:0.01
                                   target:self
                                 selector:@selector(counterTask)
                                 userInfo:nil
                                  repeats:YES];

_progressTimer =
  [NSTimer scheduledTimerWithTimeInterval:0.1
                                   target:self
                                 selector:@selector(updateViews) // heavy stuff here
                                 userInfo:nil
                                  repeats:YES];

[[NSRunLoop currentRunLoop] addTimer:_progressTimer
                           forMode:NSRunLoopCommonModes]; 

As you can see _progressTimer selector is run every 0.1 sec. One of the views is my HH:MM:SS time (data from first timer!). It display different time than real time when my progressbar is updating (heavy operation) -> 10 sec in app == 12 sec in real time... Its to much difference. When I comment my progress bar update - it all works correctly

Could you tell me how to force my timer to run exactly after my interval? Or skip one cycle when its too much for it to handle? The most important thing is to not slow down...

Thanks



via Chebli Mohamed

Select a Cell in a Storyboard created UITableView and programmatically create a UITableView and display and populate it with data

I have created a tier of three UITableViews using Storyboard and am able to move from the first to the second and then to the third. I now want to create a fourth UITableView programmatically. By selecting a Cell in the third UITableView a fourth tier UITableView must be created and displayed so that I can populate it with data. Please help. Thanks very much



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

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

How to map my Objective-C errors like Swift 2 does for NSURLError, NSCocoaError, AVError, etc. as described in WWDC 2015 video 401?

@13:20 into the WWDC video "Swift handling of Cocoa errors" (http://ift.tt/1cQOUHP) Apple shows how they have exposed their errors from Cocoa (at least some classes) as something like NSURLError.someError. These errors can then be used nicely with Swift 2 catch syntax.

This part of the video shows that this (for errors from certain Cocoa classes) is now possible:

func preflight() -> Bool {
  do {
    try url.checkResourceIsReachable()
    resetState()
    return true
  } catch NSURLError.FileDoesNotExist {
    return true // still okay
  } catch {
    return false
  }
}

Note the fact that Cocoa error NSURLErrorFileDoesNotExist is somehow mapped or usable in Swift as NSURLError.FileDoesNotExist (in the catch expression)

I'd like to have my SDK errors be able to be used in the same way.

But when I try to return an NSError from my Objective-C code, and then catch that error on the Switch 2 side, the catch block for the particular error is not invoked and the only catch block that is the ending catch-all one.

Here's how my errors are defined in Objective-C TestClass.h:

typedef NS_ENUM(NSInteger, TestClassError) {
    TestClassErrorOne,
    TestClassErrorTwo,
    TestClassErrorThree,
    TestClassErrorFour,
    TestClassErrorFive,
};

Here's how I return one of these errors in my Objective-C TestClass.m:

- (BOOL)method2AndReturnError:(NSError **)err {
    // ...

    if (err) {
        *err = [NSError errorWithDomain:@"TestClassError"
                                  code:TestClassErrorTwo
                              userInfo:nil];
        NSLog(@"set error: %@", *err);
    }
    return NO;
}

The error logged here as set in the NSError is:

[...] set error: Error Domain=TestClassError Code=1 
    "The operation couldn’t be completed. (TestClassError error 1.)"

Here's how I try to catch the error in Swift 2:

    // why are the TestClassError.xxx catch blocks not catching?
    do {
        try test.method2()
    } catch TestClassError.One {
        print("error one!")
    } catch TestClassError.Two {
        print("error two!")
    } catch TestClassError.Three {
        print("error three!")
    } catch TestClassError.Four {
        print("error four!")
    } catch TestClassError.Five {
        print("error five!")
    } catch let error as NSError {
        print("error not caught!")
        print(error)
    }

And here's how the error gets logged at the end of this (from the Swift code):

Error Domain=TestClassError Code=1 "The operation couldn’t be completed. 
    (TestClassError error 1.)"

Offhandedly I think everything looks good but the catch blocks are not "catching" the errors in the form TestClassError.Two



via Chebli Mohamed

what is typedef long dispatch_once_t in objective c

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 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

init instance variable multiple times

can this code cause any potential trouble?

@property (nonatomic, retain) NSDictionary *instanceDictionary;

for(int i = 0; i < 50; i++){
   self.instanceDictionary = [NSDictionary alloc] init];
}

or without self

for(int i = 0; i < 50; i++){
   instanceDictionary = [NSDictionary alloc] init];
}

I came across situations where a instance variable gets "overridden" like this and was wondering if it could cause any memory problems.



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

Spin Animation Resets to Original Image

For fun I have been trying to get a lottery wheel type object set up using Xcode in objective c. So far I have been able to successfully spin the object with random rotations, and stopping at 1 of 8 items on the wheel.

The problem is, I am not sure how to "save" the animation layer that is spun. Each time I spin the wheel, once the animation is completed it resets and shows the image in the original orientation. Below is the code I have setup for spinning the wheel. (NOTE: in this code I merely just have a set rotation. this is the template I am working with to try and retain the image. The other code is in a different project that stores the stopping point and corrects it to the center of on of those objects.)

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

#define SPIN_CLOCK_WISE 1
#define SPIN_COUNTERCLOCK_WISE -1

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)spinButton:(id)sender {
    [self spinLayer:_spinImage.layer duration:10 direction:SPIN_CLOCK_WISE];

}


- (void)spinLayer:(CALayer *)inLayer duration:(CFTimeInterval)inDuration
        direction:(int)direction
{
    CABasicAnimation* rotationAnimation;

    // Rotate about the z axis
    rotationAnimation =
    [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];

    // Rotate 360 degress, in direction specified
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 22.3 * direction];

    // Perform the rotation over this many seconds
    rotationAnimation.duration = inDuration;

    // Set the pacing of the animation
    rotationAnimation.timingFunction =
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

    // Add animation to the layer and make it so
    [inLayer addAnimation:rotationAnimation forKey:@"rotationAnimation"];

    // Save animation
//%%%%%%%%%%  THIS IS WHERE I AM STUCK!! %%%%%%%%%
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

If someone could just help me retain the spun image so that once the spinLayer method completes, the image stays rotated to the new spin orientation, I would greatly appreciate it. Thanks!



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

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

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

Generating Random Numbers of a certain pattern in Swift

I know that Swift can generate random numbers using this code : arc4random_uniform(50). So how can I generate random numbers in a pattern, for example : The computer should generate random numbers in the order 2,8,9,15,16,22... like any number x,x+6,x+6+1,x+6+1+6.... like that. Please help soon..! It would be a great help !



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

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