lundi 27 avril 2015

UIImage size in a tableView Cell


I have an image 1024x1024 and I want resize this image to fit into a tableView Cell. I have used this lines of code:

+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {

   //New size is the size of the cell for me
   UIGraphicsBeginImageContext(newSize);
   [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
   UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();
   NSData *imageData = UIImagePNGRepresentation(img);
   UIImage *imgFinal=[UIImage imageWithData:imageData];

   return imgFinal;

}

The problem is, when I visualize this image on the screen of Iphone6 or Iphone6+ the image appear blurred and a little bit pixelated. Can you help me?


Upload an image after 64-bit encoding


I want to upload an image on a server. I encode to 64-bit then I post. I am using this code:

NSURL *url=[[NSURL alloc] initWithString:@"http://ift.tt/1EBLi9u"];

NSMutableURLRequest *req=[[NSMutableURLRequest alloc] initWithURL:url];
[req setHTTPMethod:@"POST"];
// [req setValue:@"multipart/form-data; boundary=*****" forHTTPHeaderField:@"Content-Type"];

NSMutableData *postBody=[NSMutableData data];
NSString *boundary=@"*****";


[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSString *this=[pickedImageData base64EncodedString];

[postBody appendData: [this dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[req setHTTPBody:postBody];


NSHTTPURLResponse *response=nil;
        NSError *error=[[NSError alloc] init];

NSData *responseData;
    responseData=[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
    NSLog(@"%@",responseData);
    if(responseData&&[responseData length])
    {

        NSDictionary *dictionary=[NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
        NSLog(@"%@",dictionary);
    }
    else
    {
        NSLog(@"hello");
    }


How can I send a picture about 100kb in size to a PubNub channel in iOS SDK?


What I was doing, converting the whole image to base64 string and sending it as a message. But message sending failed each time. I got maximum payload size is 32 KB for a single PubNub message here. If I compress the image and so that my message size is less than 32 KB, will it be delivered? Is there any other API available from PubNub SDK to upload or streaming a file/image to a channel?


get view controller stack from storyboard


I try to get view-controllers array of Navigation Controller.It will returns blank array as shown below:

   UIStoryboard *mystoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPad" bundle:nil]; 
UINavigationController *nav1 = [mystoryboard instantiateViewControllerWithIdentifier:@"nav1"];
 NSLog(@"%@",nav1.viewControllers);

but this displays empty array even though it has view controller.

Thanks in advance


iphone restarts when I try to run my app


Hey I can't put any code into here because there is too much. but when I put my game onto my phone it crashes the phone and it restarts itself.
I have an iPhone 4 running 7.1.2 Xcode 6.

I'm using sprite kit with objective c. could there be anything that I have used that is only meant for iOS 8. I don't have a crash report as I don't have the developer licence.


How to connect iPhone 5s to SmartFace?


I've just installed smartface version 4.3.0

I connected my iPhone 5S to the laptop using USB cable.

I launched Smartface App Studio, clicked on Device Emulator from toolbar. Clicked on Yes button when User Account dialog appears. Progress Dialog appears, it says: "Searchign for devices... Devices found: Simon's iPhone

Keep calm ;) You need to download Smartface in action from app store and then please try again.

Same issue again? Please refer to Troubleshooting document!"

I downloaded the app on my iPhone and launched, what haven't I done?


Only I can sign into the app I have moulded in Objective C xcode. What are the possible causes of this?


I am using the latest version of FBSDKv4.0.1 in my app but only I can sign in to the app. When somebody else is trying to sign in error is obtained, why?

if ([FBSDKAccessToken currentAccessToken])
    {
        // User is logged in, do work such as go to next view controller.
        self.loginButton.readPermissions = @[@"public_profile", @"email",     @"user_friends"];
    ProgressHUD *HUD=[[ProgressHUD alloc]init];
    [HUD showTextOnlyAndHideForChat:@"Fetching details" parentView:self.view];
}

FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:@[@"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
    if (error)
    {
        // Process error
        NSLog(@"fbsdk error log");
        ProgressHUD *HUD=[[ProgressHUD alloc]init];
        [HUD showTextOnlyAndHide:@"Invalid credentials" parentView:self.view];
    }
    else if (result.isCancelled)
    {
        // Handle cancellations
        NSLog(@"fbsdk Handle cancellations");
        ProgressHUD *HUD=[[ProgressHUD alloc]init];
        [HUD showTextOnlyAndHide:@"Activity cancelled by user" parentView:self.view];
    }
    else
    {
        // If you ask for multiple permissions at once, you
        // should check if specific permissions missing
        if ([result.grantedPermissions containsObject:@"email"])
        {

            [[NSUserDefaults standardUserDefaults] setObject:[[FBSDKAccessToken currentAccessToken] tokenString] forKey:@"fbaccesstoken"];

           NSLog(@"fbaccesstoken %@",[[FBSDKAccessToken currentAccessToken] tokenString]);

//                NSDictionary *dictionaryJSON = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableLeaves error:&error];
//NSLog(@"DICTIONARY==%@\nresult===%@",dictionaryJSON,result);
            NSLog(@"fbsdk if log");
            // Do work

            ProgressHUD *HUD=[[ProgressHUD alloc]init];
            [HUD hideHudProgress];
            //------------test
            if ([FBSDKAccessToken currentAccessToken]) {
//                    ProgressHUD *HUD=[[ProgressHUD alloc]init];
//                    [HUD showHudProgressWithText:@"Fetching user information.." withView:self.view];

                [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:nil]
                 startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
                     if (!error) {

#success statements#
}

This is the error log I am getting.

Error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unauthorized (401)" UserInfo=0x7ac62bd0 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x79678040> { URL: http://ift.tt/1EbKJQy? token=(access-token-value)                                                                               { status code: 401, headers {
    Allow = GET;
    Connection = "Keep-Alive";
    "Content-Language" = en;
    "Content-Type" = "application/json";
    Date = "Sat, 25 Apr 2015 08:09:45 GMT";
    "Keep-Alive" = "timeout=5, max=100";
    Server = Apache;
    "Transfer-Encoding" = Identity;
    Vary = "Accept,Accept-Language,Cookie";
    "Www-Authenticate" = Token;
} }, NSErrorFailingURLKey=http://ift.tt/1EbKJQy?

NSLocalizedDescription=Request failed: unauthorized (401), com.alamofire.serialization.response.error.data=<7b226465 7461696c 223a2022 41757468 656e7469 63617469 6f6e2063 72656465 6e746961 6c732077 65726520 6e6f7420 70726f76 69646564 2e227d>}

Can anybody please tell me if i made a mistake in this code snippet? Or is it the bug in the latest FBSDK?


In sales and trends, why does proceeds divided by sales only = 66% and not 70%?


Recently Apple started including "sales" in iTunes Connect Sales and Trends which denotes the total revenue your app has made before Apple takes its 30% cut, while "proceeds" is what you made after the cut is subtracted.

Why is it when I take my lifetime proceeds and divide it by my lifetime sales, I only get 66-67% instead of 70%? What is happening to this other 3-4%?


Send MMS using Twilio in ios


I want to send MMS using Twilio. I am request one twilio url which is work fine on SMS but not MMS and I want to know what should change so i am sending MMS using Twilio in iOS. Here is my code.

NSLog(@"Sending request.");

// Common constants
NSString *kTwilioSID =@"Twilio SID";
NSString *kTwilioSecret =@"Twilio Secret";
NSString *kFromNumber = @"From Phone Number";
NSString *kToNumber = @"To Phone number";
NSString *kMessage=@"Hello This is Pintu vasani";

// Build request
NSString *urlString = [NSString stringWithFormat:@"https://%@:%@@api.twilio.com/2010-04-01/Accounts/%@/SMS/Messages", kTwilioSID, kTwilioSecret, kTwilioSID];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];

// Set up the body  MediaUrl
NSString *bodyString = [NSString stringWithFormat:@"From=%@&To=%@&Body=%@", kFromNumber, kToNumber, kMessage];
NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
NSError *error;
NSURLResponse *response;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

// Handle the received data
if (error) {
    NSLog(@"Error: %@", error);
} else {
    NSString *receivedString = [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
    NSLog(@"Request sent. %@", receivedString);
}


Displaying AdMob and/or iAd when switching tabs using shared banners on ios


I have an app with a UITabBarController containing 5 tabs, where each tab is a UIViewController with a UITableView embedded in. I am bringing iAds and AdMobs to my app which will be removed using IAPs. This is a universal iPhone and iPad app.

At first, I implemented just the iAds with the use of Shared Banners and the AppDelegate and it worked really well. Now, before releasing, I am going to also bring AdMobs as a fallback incase any iAds don't load. I have set it up in the same way as the iAd.

Implementing the actual AdMob is not a problem in the same way, but I am facing issues when changing tabs.

Issue

If an iAd loads and I move from the first tab to the second tab, it continues to show that iAd. If an AdMob loads and I move from the first tab to the second tab, the AdMob disappears until it reloads again.

Here's some code:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"VIEW WILL APPEAR");
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"IAPSuccessful"])
    {
        NSLog(@"View will appear and the IAP is not Successful");
        [self displayiAdsOrNot];
    }
    else
    {
        NSLog(@"View will appear and the IAP IS Successful");
        self.adBanner.hidden = YES;
        self.adMobBannerView.hidden = YES;
    }
}

- (void)displayiAdsOrNot
{
    NSLog(@"Display iAds or Not");

    self.adMobBannerView.hidden = YES;
    self.adBanner = [[self appdelegate] adBanners];
    self.adBanner.delegate = self;

    if (IDIOM == IPAD)
    {
        NSLog(@"***This is the iPad****");
        [self.adBanner setFrame:CGRectMake(0, [[UIScreen mainScreen] bounds].size.height-80, 320, 50)];
        [self.adBanner setTranslatesAutoresizingMaskIntoConstraints:NO];

        [self.view addSubview:self.adBanner];
        NSLayoutConstraint *myConstraint =[NSLayoutConstraint
                                           constraintWithItem:self.adBanner
                                           attribute:NSLayoutAttributeLeading
                                           relatedBy:NSLayoutRelationEqual
                                           toItem:self.view
                                           attribute:NSLayoutAttributeLeading
                                           multiplier:1.0
                                           constant:0];

        [self.view addConstraint:myConstraint];



        myConstraint =[NSLayoutConstraint constraintWithItem:self.adBanner
                                                   attribute:NSLayoutAttributeTrailing
                                                   relatedBy:NSLayoutRelationEqual
                                                      toItem:self.view
                                                   attribute:NSLayoutAttributeTrailing
                                                  multiplier:1
                                                    constant:0];

        [self.view addConstraint:myConstraint];

        myConstraint =[NSLayoutConstraint constraintWithItem:self.adBanner
                                                   attribute:NSLayoutAttributeBottom
                                                   relatedBy:NSLayoutRelationEqual
                                                      toItem:self.view
                                                   attribute:NSLayoutAttributeBottom
                                                  multiplier:1
                                                    constant:0];

        [self.view addConstraint:myConstraint];

    }
    else
    {
        NSLog(@"*** THIS IS THE IPHONE ***");
        [self.adBanner setFrame:CGRectMake(0, [[UIScreen mainScreen] bounds].size.height-98, 320, 50)];
        [self.view addSubview:self.adBanner];
    }

}

Here are the delegate methods:

- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
    NSLog(@"bannerViewDidLoadAd gets called");

    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"IAPSuccessful"])
    {
        NSLog(@"bannerViewDidLoadAd gets called and the IAP is not successful, so we hide the AdMob and show the iAd");
        self.adMobBannerView.hidden = YES;
        self.adBanner.hidden = NO;
    }
    else
    {
        NSLog(@"bannerViewDidLoadAd gets called and the IAP IS Successful so we hide the AdMob and iAd");
        self.adMobBannerView.hidden = YES;
        self.adBanner.hidden = YES;
    }


}

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
    NSLog(@"The didFailToReceiveAdWithError is called and it is unable to show ads in Timeline. Error: %@ %@", [error localizedDescription], [error domain]);
    self.adBanner.hidden = true; 
    [self displayAdMobBannerOrNot];
}

- (void)displayAdMobBannerOrNot
{
    NSLog(@"DisplayAdMobBannerOrNot is called");
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"IAPSuccessful"])
    {
        NSLog(@"The DisplayAdMonBannerOrNot is called and the IAP is not Successful");
        self.adMobBannerView.hidden = NO;
        self.adMobBannerView = [[self appdelegate] adMobBanners];
        self.adMobBannerView.rootViewController = self;
        self.adMobBannerView.delegate = self;

        self.adMobBannerView.adUnitID = @"ca-app-pub-394025609333333333335716";

        if (IDIOM == IPAD)
        {
            NSLog(@"The DisplayAdMobBannerOrNot is called and we are using an iPad");
            [self.adMobBannerView setFrame:CGRectMake(0, [[UIScreen mainScreen] bounds].size.height-80, 320, 50)];
            [self.adMobBannerView setTranslatesAutoresizingMaskIntoConstraints:NO];

            [self.view addSubview:self.adMobBannerView];
            NSLayoutConstraint *myConstraint =[NSLayoutConstraint
                                               constraintWithItem:self.adMobBannerView
                                               attribute:NSLayoutAttributeLeading
                                               relatedBy:NSLayoutRelationEqual
                                               toItem:self.view
                                               attribute:NSLayoutAttributeLeading
                                               multiplier:1.0
                                               constant:0];

            [self.view addConstraint:myConstraint];

            myConstraint =[NSLayoutConstraint constraintWithItem:self.adMobBannerView
                                                       attribute:NSLayoutAttributeTrailing
                                                       relatedBy:NSLayoutRelationEqual
                                                          toItem:self.view
                                                       attribute:NSLayoutAttributeTrailing
                                                      multiplier:1
                                                        constant:0];

            [self.view addConstraint:myConstraint];

            myConstraint =[NSLayoutConstraint constraintWithItem:self.adMobBannerView
                                                       attribute:NSLayoutAttributeBottom
                                                       relatedBy:NSLayoutRelationEqual
                                                          toItem:self.view
                                                       attribute:NSLayoutAttributeBottom
                                                      multiplier:1
                                                        constant:0];

            [self.view addConstraint:myConstraint];

        }
        else
        {
            NSLog(@"The DisplayAdMobBannerOrNot is called and we are using an iPhone");
            [self.adMobBannerView setFrame:CGRectMake(0, [[UIScreen mainScreen] bounds].size.height-98, 414, 50)];

            [self.view addSubview:self.adMobBannerView];

                GADRequest *request = [GADRequest request];
                request.testDevices = @[ @"151111111111ffb836f4d823ac" ];
                [self.adMobBannerView loadRequest:request];
        }
    }
    else
    {
        NSLog(@"The DisplayAdMobBannerOrNot is called and the IAP IS Successful so we'll just hide the iAd and the adMobBanner");
        self.adBanner.hidden = YES;
        self.adMobBannerView.hidden = YES;
    }
}

So, when the viewWillAppear gets called (every time I come back to this UIViewController), I am checking if the IAPSuccessful bool is true. If it's not, I load up the displayiAdsOrNot method. If that fails, it's delegate will get called which calls the displayAdMobBannerOrNot.

Now, I completely understand why, when I have an AdMob displaying and I move from one view to another, it removes the AdMob because when I come back, the viewWillAppear loads up the sharedBanner for the iAd and not the AdMob.

With that in mind, I'm not really sure what I need to do. I want to ensure the AdMob is loading the sharedBanner every time it's loaded. So I put the sharedBanner code from the displayAdMobBannerOrNot into the displayiAdOrNot and it didn't change the behaviour, because it's not calling the functionality to actually place the ad (displayAdMobBannerOrNot).

As a test, in the viewWillAppear, when the IAPSuccessful is false, I called [self bannerView:self.adBanner didFailToReceiveAdWithError:nil]; instead of anything else and that worked. When I moved from tab one to two two, it kept the AdMob in display. However, that's of course not productional code. I'm just not able to see this clearly.

Any guidance on this would really be appreciated.


How to AutoLayout the buttons in uiview controller in iphone?


I have size of 4 inch and i have added 4 icons in 3 different rows of all equal size 60x60. I can have a proper view in iphone 4s,5,5s but not in iphone 6 and 6 plus. So how can i apply auto layout to it and make the icons look bigger and of same ratio in iphone 6 and 6 plus. Can this be made without any coding?

Like this enter image description here

This buttons should change its size in iphone 6 and 6 plus i.e. it should get bigger and proper aligned. Can it is possible without coding?


UIViewController in iOS app launch screen


Is it possible to add a view controller to launch screen in iOS ? if yes How could i do that ?

I have dragged a UIViewController to the LaunchScreen.xib file its run correctly, but when i changed the class for the view controller in the LaunchScreen.xib from "identity inspector" from UIViewController to myLaunchScreenViewControllerName i faced this error

Illegal Configuration : Launch screen may not use instance of myLaunchScreenViewControllerName

if you can help me I will be thankful for you thanking in advance :)


Notification in iPhone banner


When we send a push notification to app it automatically added to banner and show to user. But I want to show message in banner from app to user.

Is it possible, If yes how can do this?


iOS: UITableView cells gets mixed up while scrolling


I am facing one issue regarding UITableView cells get mixed up while scrolling, specially for images.

I am not sure why this is going one.
I have change the patter for displaying then also its get mixed up.
Below is my code.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"FriendsCell";
    FriendsTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FriendsTableCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    FriendsTableCell *simpleTableCell = (FriendsTableCell *)cell;

    _model = [_contentArray objectAtIndex:indexPath.row];

    simpleTableCell.nameLabel.text = _model.fullname;

    if(_friendsSegmentControl.selectedSegmentIndex == 0) {

        simpleTableCell.followButton.hidden = NO;
        simpleTableCell.removeButton.hidden = NO;
        simpleTableCell.unBlockButton.hidden = YES;
        simpleTableCell.ignoreRequest_btn.hidden = YES;
        simpleTableCell.rejectRequest_btn.hidden = YES;
        simpleTableCell.acceptRequest_btn.hidden = YES;

        simpleTableCell.removeButton.tag = indexPath.row;
        [simpleTableCell.removeButton addTarget:self action:@selector(deleteFriend_btn:) forControlEvents:UIControlEventTouchUpInside];

        simpleTableCell.followButton.tag = indexPath.row;

        if([_model.isfollowed isEqualToString:@"YES"]) {
            [simpleTableCell.followButton setImage:[UIImage imageNamed:@"follow_yellow.png"] forState:UIControlStateNormal];
            [simpleTableCell.followButton addTarget:self action:@selector(unfollowFriend_btn:) forControlEvents:UIControlEventTouchUpInside];
        }
        else {
            [simpleTableCell.followButton setImage:[UIImage imageNamed:@"follow_white.png"] forState:UIControlStateNormal];
            [simpleTableCell.followButton addTarget:self action:@selector(followFriend_btn:) forControlEvents:UIControlEventTouchUpInside];
        }
    }

    NSString *escapedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(__bridge CFStringRef) _model.prof_pic,NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8));

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^(void) {

        NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://ift.tt/1QyVOl3",escapedString]]];
        UIImage *image = [UIImage imageWithData:imageData];
        dispatch_async(dispatch_get_main_queue(), ^{
            simpleTableCell.profileImageView.image = image;
        });
    });

}


NSDateComponents.quater is returning 0 instead of valid quater count


NSDateComponents.quater is returning 0 instead of valid quater count.

I googled and it is said it is a bug for apple found in 2012. However, now it is 2015 and iOS 8.3, bug still exists.

for example:

unitFlags = NSQuarterCalendarUnit;

(lldb) po firstDate
2009-12-31 16:00:00 +0000

(lldb) po lastDate
2013-09-30 16:00:00 +0000

(lldb) po [gregorian components:unitFlags fromDate:firstDate toDate:lastDate options:0];
<NSDateComponents: 0x170158b50>
    Quarter: 0


How to create custom UIView according to uploaded image in iOS?


I want to create custom UIView in my iOS app and my custom UIView like this kind of image type .enter image description here


Has anything changed with custom UITableView prototype cells constraints since iOS 8.3?


I have recently installed iOS 8.3 on my iPhone (I had iOS 8.1 before).

I also updated the iOS SDK from iOS 8.1 to iOS 8.3.

Since I updated it some custom prototype cells I had seem to be misplaced.

Has anything changed from iOS 8.1 to iOS 8.3 regarding the way constraints are handled?


dimanche 26 avril 2015

Size of UIScrollView and Size of Images


I have created this scrollview that loads the images dynamically. However I cannot get the images to cover the screen (should adapt to iPhone/iPad) one and one. And the height of the images is also corrupt (see attached image)

What am I doing wrong?

Image

enter image description here

Source to load images:

 for (int i=0; i < numberOfImages; i++) {

        // create image
        NSString *imageName = [NSString stringWithFormat: imageArray[i], i+1];
        UIImage *image = [UIImage imageNamed:imageName];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

        // put image on correct position
        CGRect rect = imageView.frame;
        rect.origin.x = currentX + self.scrollView.frame.size.width/2;
        imageView.frame = rect;

        // update currentX
        currentX += imageView.frame.size.width + self.scrollView.frame.size.width;

        [self.scrollView addSubview:imageView];
        [imageView release];
    }

    self.scrollView.contentSize = CGSizeMake(currentX, self.view.frame.size.height);

    self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    [self.view addSubview:scrollView];
    [self.scrollView release];


Read verification code automatically and access for Login in App in iOS


I am creating one App and it has verification phone number required functionality which allow user to enter into App. We send sms to the Users through the gateway and we need to read verification code directly from the SMS without typing code into App. But don't know how to read verification code automatic from the SMS and access in my App.I have gone thorugh the searches for this but could not find any path to move ahead. Is it allow in iOS and if Yes, can anyone tell me what to do to achieve it. Thanks.


Get total number of annotations of visible cluster/s in mkmapview


Can anyone help me with MKMapViews. I am using the FBAnnotations/FBClustering.

My issue is, for example, lets say I have 20 annotations and is clustered in to 4. I have 2 clusters visible in the map, cluster A with 3 annotations and cluster B with 4 annotations.

I want the total of cluster A and B be the title of the view controller (in my case it should be 7).
Instead of getting 7 I keep getting the total number of annotations in my map.

I uploaded an image, please click here.
Here's what i've got so far:
This is the method in my MKMapView view controller:

- (void)mapViewWithJobsDisplayed:(NSDictionary *)jobsDictionary andUserLocation:(CLLocation *)location andUserCoordinates:(CLLocationCoordinate2D)locationCoordinates
{   
    if(locationCoordinates.latitude == 0.0f || locationCoordinates.longitude==0.0f)
    { 
    }
    else
    {
        ar = [jobsDictionary objectForKey:@"sub_slots"];

        //Save location
        userLocation = location;
        userLocationCoordinates = locationCoordinates;

        // Initiate cluster array
        clusterArray = [[NSMutableArray alloc] initWithCapacity:ar.count];

        for (int i = 0; i < ar.count; i++) {
            NSDictionary *jobPin = [ar objectAtIndex:i];
            latitude = [[jobPin objectForKey:@"sub_slots"] objectForKey:@"latitude"];
            longitude = [[jobPin objectForKey:@"sub_slots"] objectForKey:@"longitude"];
            companyName = [[jobPin objectForKey:@"sub_slots"] objectForKey:@"company_name"];
            companyAddress = [[jobPin objectForKey:@"sub_slots"] objectForKey:@"address"];

            CLLocationCoordinate2D coordinate;
            coordinate.latitude = [latitude doubleValue];
            coordinate.longitude = [longitude doubleValue];

            if([latitude doubleValue] == 0.0f || [longitude doubleValue]==0.0f)
            {
            }
            else
            {
                MyLocation *annotation = [[MyLocation alloc] initWithName:companyName address:companyAddress coordinate:coordinate];
                [annotation setTagNumber:i];
                [self addAnnotation:annotation];
                [clusterArray addObject:annotation]; 
            }
        }

        //Create clustering manager
        clusteringManager = [[FBClusteringManager alloc] initWithAnnotations:clusterArray];
        clusteringManager.delegate = self;
        [self refreshMapView];
    }
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    MKAnnotationView *av = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"JobsPins"];

    UIImage *backgroundImage = [UIImage imageNamed:@"pinMap"];
    if ([annotation isKindOfClass:[FBAnnotationCluster class]])
    {
        FBAnnotationCluster *cluster = (FBAnnotationCluster *)annotation;
        cluster.title = [NSString stringWithFormat:@"%lu", (unsigned long)cluster.annotations.count];
        av.canShowCallout = YES;
        UIImage *frontImage = [self drawTextWithStroke:cluster.title andImage:backgroundImage];
        av.image = [self placeImage:frontImage onImage:backgroundImage];
        // Check zoom level and show accessory button
        NSUInteger zoomLevel = [self zoomLevelForMapRect:mapView.visibleMapRect withMapViewSizeInPixels:mapView.bounds.size];

        if (zoomLevel > 1) {
            av.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        }

        return av;
    }

    if ([annotation isKindOfClass:[MyLocation class]])
    {
        av.canShowCallout = YES;
        UIImage *frontImage = [self drawTextWithStroke:@"1" andImage:backgroundImage];
        av.image = [self placeImage:frontImage onImage:backgroundImage];
        av.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

        return av;
    }

    return nil;
}


Why swift app IPA crashes when I open the app ?


I have created app in Swift language and install that IPA (Distribution profile) on the my iPad, the app getting crash. But I run through debug mode its running correctly on the same device. Can you give the solutions for this crashing ? and How do I fix this issue ?

Xcode version : 6.3.1 iOS version : 8.3

Crash log in device :

Apr 26 23:12:46 My-iPad kernel[0] <Notice>: xpcproxy[445] Container: /private/var/mobile/Containers/Data/Application/0E13BE10-CBAC-45FF-AAB9-575F87B32216 (sandbox)
Apr 26 23:12:46 My-iPad kernel[0] <Notice>: AMFI: TestApp(pid 445) - [deny-mmap] mapped file has no team identifier and is not a platform binary: /private/var/mobile/Containers/Bundle/Application/CFDED3C6-7AF6-427B-BBFC-27E9186EF590/http://ift.tt/1EvEU1L
Apr 26 23:12:46 My-iPad ReportCrash[411] <Notice>: ReportCrash acting against PID 445
Apr 26 23:12:46 My-iPad ReportCrash[411] <Notice>: Formulating crash report for process TestApp[445]
Apr 26 23:12:46 My-iPad com.apple.xpc.launchd[1] (UIKitApplication:com.mobility.TestApp[0x3c28][445]) <Notice>: Service exited due to signal: Trace/BPT trap: 5
Apr 26 23:12:46 My-iPad SpringBoard[49] <Warning>: LICreateIconForImage passed NULL CGImageRef image
Apr 26 23:12:47 My-iPad ReportCrash[411] <Notice>: Saved report to /var/mobile/Library/Logs/CrashReporter/TestApp_2015-04-26-231246_My-iPad.ips
Apr 26 23:12:47 My-iPad locationd[56] <Notice>: Gesture EnabledForTopCLient: 0, EnabledInDaemonSettings: 0
Apr 26 23:12:47 My-iPad SpringBoard[49] <Warning>: Application 'UIKitApplication:com.mobility.TestApp[0x3c28]' crashed.
Apr 26 23:12:47 My-iPad locationd[56] <Notice>: Gesture EnabledForTopCLient: 0, EnabledInDaemonSettings: 0


Core Bluetooth Framework: Incorrect value of battery characteristic


I have created an application in IPhone that can act as a Peripheral. I have added several Services and Characteristics.For Battery characteristic, I have used the standard UUID "2A19". All other characteristic values are coming correctly in Central device except battery. It is showing 0 while i have given the value 60.Their is a possibility that it is colliding with IPhone battery characteristic. So is their any way to correct it ?


Date Converting


I have a String 30-07-2013 I want to converted in to 30 June. I am using

 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"dd/MM/YYYY"];
    NSDate *date = [dateFormat dateFromString:@"30-07-1983"];
They Show response -1984-12-24 18:06:32 +0000


How to integrate native ios app design for all iPhones


I am doing Bus ticket booking app. I want to integrate for all iphones. I am facing design problem. how to set image for all iphones.

Thanks in advance


Why zoom jqplot doesn't work on mobile phone (Android, iPhone,....)?


If you try Zoom Jqplot Example with your PC (Firefox, Chrome,...) the zoom works correctly.

But when I try it from mobile phones (iPhone, Android with Chrome,...) it doesn't work!!

Any help is appreciated!!


Tableview reloadRowsAtIndexPaths gain to 50% CPU Memory?


I have an issue where I have a UITableViewController and when the view appears I do some calculations asynchronously which should result in the updating of specific rows in the table.

Inside the cellStartEditing function I calculate the necessary rows that need to be updated as follows:

-(void) cellStartEditing:(templateRow *) row{
    int Cellowid= row.rowId;
    [arrQuestions removeObjectAtIndex:CellRowid];
    [arrQuestions insertObject:row atIndex:CellRowid];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow: inSection:0];
    [tvQuestion reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

At that time reloadRowsAtIndexPaths Animation gain to 50% CPU Memory ?


Adobe AIR ios app black screens at startup (IOS 8.3)


I am trying to port an app I made for Android over to ios. My certificate and PP are linked properly and it syncs onto my phone from iTunes.

However, when I try to open it on my iPhone it shows a black screen and then closes immediately. I've tried it with an empty project and nothing changed so I don't think the problem is with the code.

I'm using Flash Professional CC 2014 and AIR 17.0.0.144. If I export it in Flash Professional CS6 it doesn't crash but keeps the black screen.


Change frame size of table programmatically


I am trying to do the example on http://ift.tt/1GyxexT where I am putting json values. I used navigational bar but then the header data is getting hidden. I tried changing the frame size in XCMultiSortTableView.m file but the position of header doesn't change. I am getting output as

enter image description here

But I want the output where years is displayed along with navigational bar as

enter image description here

Please do reply.


Get Notification when iPhone silent On or Off in objective c


My application is running mode. and i want to check in running mode.Means when user set on/off ,i want to get any notification to handle it.

My requirement is when user set silent mode of iPhone Lable color should be change.

So how I get listener when user set mode on/off of silent switch?


Black Screen when attempting to use MPMoviePlayer


I am using MPMoviePlayer to display a video from an external URL onto my iPhone App, however when I run the App a black screen is all that shows. Here is the URL I am using:

2015-04-27 00:11:29.655 Floadt[21069:2598414] http://ift.tt/1HMhFmp

Here is my code to try to setup MPMoviePlayer:

if (entry[@"videos"] != nil) {
    NSLog(@"There is a Video: %@", entry[@"videos"]);
    NSString *urlString = entry[@"videos"][@"standard_resolution"][@"url"];
    NSLog(urlString);
    NSURL *url = [NSURL URLWithString:urlString];
    MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL: url];
    [player prepareToPlay];
    [player.view setFrame: CGRectMake(10, 65, 299, 299)];
    [cell.contentView addSubview: player.view];
    player.shouldAutoplay = YES;
    [player play];
}


IOS XCODE crash with error : Dispatch queue: com.apple.root.default-qos


I am getting error "Dispatch queue: com.apple.root.default-qos
Exception Type:        EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       KERN_INVALID_ADDRESS at 0x0000000000000010"
when i run a project. 
I installed MAC in VMWare and installed xcode 6.1.

Is anyone encounter this issue and any resolution for this issue.

Below is full crash report:
Process:               Xcode [299]
Path:                  /Applications/http://ift.tt/1kAnkB8
Identifier:            com.apple.dt.Xcode
Version:               6.3.1 (7703)
Build Info:            IDEFrameworks-7703000000000000~4
App Item ID:           497799835
App External ID:       812230896
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           Xcode [299]
User ID:               501

Date/Time:             2015-04-26 19:36:47.627 -0700
OS Version:           Mac OS X 10.10 (14A238x)
Report Version:        11
Anonymous UUID:        F379DDE0-7D57-C054-0C16-360F7F63CAE3


Time Awake Since Boot: 230 seconds

Crashed Thread:        11  Dispatch queue: com.apple.root.default-qos

Exception Type:        EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       KERN_INVALID_ADDRESS at 0x0000000000000010

   VM Regions Near 0x10:
   --> 
   __TEXT                 0000000109edf000-0000000109ee0000 [    4K] r-x/rwx SM=COW  /Applications/http://ift.tt/1kAnkB8         
Application Specific Information:
ProductBuildVersion: 6D1002

Thread 0:: Dispatch queue: com.apple.main-thread
0   libsystem_kernel.dylib          0x00007fff8c5a35ae mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff8c5a275f mach_msg + 55
2   com.apple.CoreFoundation        0x00007fff8ad78d64    __CFRunLoopServiceMachPort + 212
3   com.apple.CoreFoundation        0x00007fff8ad78255 __CFRunLoopRun + 1381
4   com.apple.CoreFoundation        0x00007fff8ad77aa8 CFRunLoopRunSpecific + 296
com.apple.HIToolbox             0x00007fff869e3b3f RunCurrentEventLoopInMode   + 235

6 com.apple.HIToolbox 0x00007fff869e38b2 ReceiveNextEventCommon + 431 7 com.apple.HIToolbox 0x00007fff869e36f3 _BlockUntilNextEventMatchingListInModeWithFilter + 71 8 com.apple.AppKit 0x00007fff89453825 _DPSNextEvent + 1000 9 com.apple.AppKit 0x00007fff89452ff9 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 139 10 com.apple.dt.DVTKit 0x000000010a633dda -[DVTApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 237 11 com.apple.AppKit 0x00007fff89446fe3 -[NSApplication run] + 594 12 com.apple.AppKit 0x00007fff89432a9e NSApplicationMain + 1778 libdyld.dylib 0x00007fff8cc055c9 start + 1

Thanks


Creating a fullscreen UIView programmatically?


I am trying to programmatically create a new UIView for loading and set parameters in code. Basically the view will be very simple. Literally all I need is an UIView that is fullscreen and has an image in the middle. I want this so that I can call a global function whenever anything is loading and show a white screen with a loading image. I do not want to make the view inside the XIB because I will have to add it to dozens of existing XIB's.

I have read a few posts on here most of them outdated, what is the simplest way I can create a fullscreen UIView with a solid color. Im sure I can figure out the image part myself.


Changing a fill color on ellipse using Objective-C


I am overriding drawRect method in order to draw ellipse

- (void)drawRect:(CGRect)rect {

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetLineWidth(context, 2.0);

CGContextSetStrokeColorWithColor(context, [UIColor mainColorYellow].CGColor);

CGRect rectangle = CGRectMake(0.0, 2.0, rect.size.width , rect.size.height - 4.0);

CGContextAddEllipseInRect(context, rectangle);

CGContextStrokePath(context);

}

How can I change fill color on ellipse? I tried using CGContextSetFillColorWithColor(CGContextRef c, CGColorRef color) but without result.


Swift: Adding UIImage?


How do I add an image via Swift with the UIImage command? This is my current code:

var imageView = UIImageView(frame: CGRectMake(100, 100, 150, 150));     
myPic = UIImage(named: "bowling");
imageView.image = myPic;
self.view.addSubview(imageView);

It does not show anything, and this is under viewDidLoad(), which should load by default.

Thanks! :)


Private unique device identifier in iOS


We're working on a project with my colleagues which involves using a lot of private and non official code. This is not intended for AppStore use.

The first and only requirement we have is to not use jailbreak.

First of all, UDID or OpenUDID or any other solutions don't work here and they're not expected to.

We've done a lot of background research and tests, starting with trying to get the IMEI, ICCID, IMSI and the Serial Number programatically. None of the above methods work with iOS 7 and above without jailbreak.

We've also spent a couple of months to play with IOKit framework using the famous IOKitBrowser and dumping the whole contents of iOS internals. Unfortunately, we discovered that with iOS 8.3 it stopped working.

We're talking here not about getting the UDID or any other "mainstream" thing, but generally speaking we need a way to get

any permanent hardware identifier unique enough to identify a device that would persist in spite of device wipes and amongst different iOS versions

This question is no duplicate to others (no solutions are found here, for example) and is targeting solely private APIs.

Any help would be highly appreciated.


UILabel getting added multiple times on UITableViewCell


I am having a UITableViewCell which is displaying data from a JSON Array consisting of Instagram Pictures. However the UITableViewCell is messed up in the sense that each corresponding Cell has the prior Cells data on top of it. Its more of a UI issue rather than actual web API issue. This issue can best be shown in a picture so I have provided one belowenter image description here Here is the code I am using:

   UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"InstaCell"];
    cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Background.png"]];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"InstaCell"];
    }

    NSDictionary *entry = instaPics[indexPath.row];

    //
    // SETUP VIEWS
    //

    // Name
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(73, 6, 192, 25)];
    [self.nameLabel setFont:[UIFont fontWithName:@"Helvetica-Regular" size:16.0]];


    // Profile Pic
    self.profilePic = [[UIImageView alloc] initWithFrame:CGRectMake(10, 6, 50, 50)];


    // Date Label
    self.dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(68, 29, 192, 21)];
    [self.dateLabel setFont:[UIFont fontWithName:@"Helvetica-Light" size:12.0]];


    // Like Button
    self.likeButton = [[UIButton alloc] initWithFrame:CGRectMake(68, 279, 18, 18)];
    [self.likeButton setBackgroundImage:[UIImage imageNamed:@"heartShape.png"] forState:UIControlStateNormal];
    [self.likeButton addTarget:self action:@selector(didTapLikeButton:) forControlEvents:UIControlEventTouchUpInside];


    // Comment Button
    self.commentButton = [[UIButton alloc] initWithFrame:CGRectMake(68, 29, 192, 21)];


    // Like Label
    self.likeLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 371, 50, 21)];
    self.likeLabel.font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:14];
    self.likeLabel.textColor = [UIColor orangeColor];


    // Heart Icon
    self.heartIcon = [[UIButton alloc] initWithFrame:CGRectMake(20, 375, 14, 14)];
    [self.heartIcon setBackgroundImage:[UIImage imageNamed:@"heart.png"] forState:UIControlStateNormal];
    [self.heartIcon setTitleColor:[UIColor grayColor]
                         forState:UIControlStateHighlighted];
    [self.heartIcon addTarget:self action:@selector(didTapLikeIcon:) forControlEvents:UIControlEventTouchUpInside];


    // Comment Icon
    self.commentIcon = [[UIButton alloc] initWithFrame:CGRectMake(20, 395, 14, 14)];
    [self.commentIcon setBackgroundImage:[UIImage imageNamed:@"comment.png"] forState:UIControlStateNormal];
    [self.commentIcon setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [self.commentIcon addTarget:self action:@selector(didTapCommentIcon:) forControlEvents:UIControlEventTouchUpInside];


    // Comment Text
    self.commentText = [[UILabel alloc] initWithFrame:CGRectMake(-88, 370, 259, 40)];
    [[self.commentText layer] setAnchorPoint:CGPointMake(0, 0)];
    self.commentText.font = [UIFont fontWithName:@"HelveticaNeue" size:14];
    self.commentText.lineBreakMode = NSLineBreakByWordWrapping;
    self.commentText.numberOfLines = 3;
    self.commentText.textColor = [UIColor blackColor];


    // Location Icon
    self.locationIcon = [[UIButton alloc] initWithFrame:CGRectMake(73, 33, 12, 12)];
    [self.locationIcon setBackgroundImage:[UIImage imageNamed:@"location.png"] forState:UIControlStateNormal];
    [self.locationIcon setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [self.locationIcon addTarget:self action:@selector(didTapLocationIcon:) forControlEvents:UIControlEventTouchUpInside];


    // Heart Button
    self.heartButton = [[UIButton alloc] initWithFrame:CGRectMake(40, 465, 25, 25)];
    [self.heartButton setBackgroundImage:[UIImage imageNamed:@"heart.png"] forState:UIControlStateNormal];
    [self.heartButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];


    // Comment Button
    self.commentButton = [[UIButton alloc] initWithFrame:CGRectMake(220, 465, 25, 25 )];
    [self.commentButton setBackgroundImage:[UIImage imageNamed:@"comment.png"] forState:UIControlStateNormal];
    [self.commentButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];


    //
    // ADD DATA
    //

    // Set User Name
    NSString *user = entry[@"user"][@"full_name"];
    [self.nameLabel setText:user];

    // If no Caption
    if (entry[@"caption"] != [NSNull null] && entry[@"caption"][@"text"] != [NSNull null])            {
        NSString *caption = entry[@"caption"][@"text"];
        [self.commentText setText:caption];
    }else{
        NSString *caption = @"";
        [self.commentText setText:caption];
    }

    // Set the number of likes
    NSString *likesCount = entry[@"likes"][@"count"];
    NSString *likes = [NSString stringWithFormat: @"%@", likesCount];
    [self.likeLabel setText:likes];

    // Add Profile Image
    NSURL *imageUrl = entry[@"user"][@"profile_picture"];
    [self.profilePic sd_setImageWithURL:imageUrl completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        self.profilePic.image = image;
        //Make the Profile Pic ImageView Circular
        CALayer *imageLayer = self.profilePic.layer;
        [imageLayer setCornerRadius:25];
        [imageLayer setMasksToBounds:YES];
    }];

    //NSString *latitude = entry[@"location"][@"latitude"];
    //NSString *longitude = entry[@"location"][@"longitude"];

    //if ([[entry objectForKey:@"location"] objectForKey:@"latitude"] == NSNotFound) {
      // NSLog(@"Contains Location");
    //}

    [self.commentButton addTarget:self action:@selector(commentButtonTap:) forControlEvents:UIControlEventTouchUpInside];
    [self.likeButton addTarget:self action:@selector(likeButtonTap:) forControlEvents:UIControlEventTouchUpInside];

    NSDictionary *instapic = [self.instaPics objectAtIndex:indexPath.row];

    // Comparator to determine if their are any videos availible 
    if (entry[@"videos"] != nil) {
        // Set Videos
        NSLog(@"there are videos: %@", entry[@"videos"]);
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        _playerView = [[GUIPlayerView alloc] initWithFrame:CGRectMake(10, 65, 299, 299)];
        [_playerView setDelegate:self];

        [[self view] addSubview:_playerView];

        NSString *urlstring = entry[@"videos"][@"standard_resolution"][@"url"];

        NSURL *URL = [NSURL URLWithString:urlstring];
        [_playerView setVideoURL:URL];
        [_playerView prepareAndPlayAutomatically:YES];
    }else{
        // Set Image
        self.instagramPic = [[UIImageView alloc] initWithFrame:CGRectMake(10, 65, 299, 299)];
        NSString *imageUrlString = entry[@"images"][@"low_resolution"][@"url"];
        NSURL *url = [NSURL URLWithString:imageUrlString];
        [self.instagramPic sd_setImageWithURL:url];

    }

    //
    // ADD ALL SUBVIEWS
    //

    [cell addSubview:self.commentButton];
    [cell addSubview:self.nameLabel];
    [cell addSubview:self.profilePic];
    [cell addSubview:self.instagramPic];
    [cell addSubview:self.dateLabel];
    [cell addSubview:self.likeButton];
    [cell addSubview:self.commentButton];
    [cell addSubview:self.likeLabel];
    [cell addSubview:self.heartIcon];
    [cell addSubview:self.commentIcon];
    [cell addSubview:self.commentText];
    [cell addSubview:self.locationIcon];
    [cell addSubview:self.heartButton];

    return cell;


CSS coding to that will show up correctly on ipad and iphone


Hello I have recently uploaded a new website, and I am currently testing the site and fixing the bugs, Currently the site looks fine in IE and Firefox, but when I view the site on my Iphone and ipad, it looks totally different.

Please help, and many thanks in advance.

/*
----------------------------------------------------------------*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}

/* END: RESET / DEFAULT */

/*---------------------------------------------------------*/

/*= GENERAL STYLING
--------------------------------------------------------*/
@media screen and (max-width:959px){
#slide1, #slide2, #slide3, #slide4{
width:100%;
}
#header {
width:80%;
 }
}

@media screen and (max-width:640px){
#slide1, #slide2, #slide3, #slide4
width:100%;
}
#header {
width:100%;
 }
}

@media screen and (max-width:320px){
#slide1, #slide2, #slide3, #slide4{
width:320px;
}
#header {
width:320%;
 }
}

body{
    margin: 0;
    padding: 0;
    width: 100%;
}

h1 { 
    font-family:"Source Sans Pro";
    font-weight:normal;
    font-size: 55px;
    text-align: center;
    color: #fff;
    margin: 0;
    padding: 0;
}

h2 {
   font-family:"Source Sans Pro";
   font-weight: normal;
   font-size: 40px;
   text-align: center;
   color: #fff;
   margin: 0;
    padding: 0;
}

h3 {
   font-family: "Source Sans Pro";
   font-weight: normal;
   font-size: 16px;
   text-align: center;
   margin: 5px 0;
    padding: 0;
    z-index: 1;
    position: relative;
}



.center { margin: 0 auto; }
.content{ margin: 0 auto; width: 960px; }

.content_table
{ margin: 10px 0 0 280px; 
width: 960px; 
}
.clear { clear: both; }
a.lpanel { float: left; color: #e1e1e1; font-size: 12px; font-family:"Source Sans Pro"; text-decoration: none; margin: 7px 11px; }
a.rpanel { float: right; color: #e1e1e1;  font-size: 12px; font-family:"Source Sans Pro"; text-decoration: none; margin: 7px 11px; }

a.lpanel:hover{ color: #fff; }
a.rpanel:hover{ color: #fff; }
/*= HEADER & NAVIGATION
--------------------------------------------------------*/

#header { 
    width: 100%; 
    background: url('../img/header-bg.png'); 
    height: 80px;   
    position: fixed;
    margin-top: 30px;
}

#nav { width: 410px; float: right; margin-top: 20px; }

#logo a { 
float: left; 
position:absolute;
margin-top: 5px 400px 0 0;  
}



#nav ul{
    list-style: none;
    display: block;
    margin: 0 auto;
    list-style: none;   
}

#nav li{
    margin-top: 9px;    
    float: left;
    padding-left: 21px;
}

#nav li a { color: #fff; opacity:0.6; font-size: 16px; text-decoration: none; font-family: "Source Sans Pro"; }
#nav li a.active { color: #fff; opacity:1; border-bottom: 2px solid #fff; }
#nav li a:hover { color: #fff; opacity:1;  }



/*= QUOTES AND SOME ELEMENTS
--------------------------------------------------------*/
.quotes {   
 font-family: "Source Sans Pro";
   font-weight: normal;
   font-size: 50px;
  text-align: left;
  margin: 50px auto;
}

 .author_name_bass { font-family:"Source Sans Pro";  margin: 5px 0 0 500px; 
 color: #fff; 
 font-size: 15px; 
 } 

#position_a
{

position:relative;
margin-bottom:-400px;
} 

 .quotes_container 
 { width: 800px; 
 height:500px;
 margin: 0 auto; 

 }

 #cta1 {   
  font-family: 'Source Sans Pro';
   font-weight: normal;
   font-size: 20px;
   float:left;
}



/*= BUTTONS
--------------------------------------------------------*/

button.btn-know { 
    padding: 15px 47px; 
    margin: 40px 38.8%;
    text-align: center;
    border: 4px solid #fff; 
    color: #fff; 
    background: transparent; 
    font-size: 19px;
    cursor: pointer;
    text-shadow: -1px 2px 0px rgba(90, 90, 90, 0.56);
    -webkit-border-radius: 4px;
    border-radius: 4px;
}

.btn-know:hover { background: #fff; color: transparent; }
ul.built { list-style: none; margin: 0 auto; width: 730px; }
.built li img{ float: left; padding-right: 34px; }



/*= SLIDES STYLING
--------------------------------------------------------*/

#slide1, #slide2, #slide3, #slide4{ width: 100%; }
#slide1{
    background:url('../img/slide1.png') 50% 0 no-repeat fixed;
    color: #fff;
    height: 300px;
    margin: 0;
    padding: 100px 0 260px 0;
    background-size: cover;
}

#slide2{
    background-color: #fff;
    color: #333333;
    height: 720px;
    margin: 0;
    overflow: hidden;
    padding: 100px 0;
}

#slide3{
    background: url('../img/slide3.png') 50% 0 no-repeat fixed;
    color: #fff;
    height: 700px;
    padding: 60px 0 0 0;    
    background-size: cover;
}




#slide4{
    background-color: #fff;
    color: #333333;
    height: 200px;
    padding: 60px 0;
}

#about{
 font-family: 'Source Sans Pro';
   font-weight: normal;
   font-size: 16px;
  text-align: left;
  margin: 50px 0 0 250px;
 }


#table_position{ 
margin: 50px 0 0 525px; 
width: 500px; 
background-color:#ffffff;
}

/*= Contact Form STYLING
--------------------------------------------------------*/
#con_pos{
background-color:e1e1e1;
margin-right:300px;
}


h1
{
font-family: 'Source Sans Pro';
font-size: 30px;
text-transform: uppercase;
color: #ee2b7b;
}


/* Centres the page (this could be container)*/
.body {
    display:block;
    margin:0 auto;
    width:576px;
    font-family: 'Source Sans Pro';
    font-size: 16px;
    color: #999;
}

#title4{
width:300px;
height:35px;
margin: 0 60px 0 0;
}


/* Labels are titles for the text fields. You can use a placeholder instead if you like*/
label
{
    display:block;
    margin-top:20px;
    letter-spacing:2px;
    font-family: 'Source Sans Pro';
}

/* Centres the form within the page */
form 
{
    margin:0 auto;
    width:459px;
}

/* Styles the text boxes */
input, textarea, file {
    width:400px;

    background-color:#efefef;
    border-radius:5px;
    -moz-border-radius:5px;
    -webkit-border-radius:5px;
    border:1px solid #dedede;
    padding:10px;
    margin-top:3px;
    font-size:0.9em;
    color:#3a3a3a;
}

.button{
width:65px;
cursor:pointer;
color:#999999;
font-family: 'Source Sans Pro';
}

    input:focus, textarea:focus {
        border:1px solid #97d6eb;
    }

/* Styles the text area boxes (message field) */    
textarea 
{
    height:200px;
    background-color: #efefef;
}


/* Styles the submit button */
#submit {
    /* background:url(images/submit.png); */
    width:127px;
    height:48px;
    text-align: center;
    /* text-indent:-9999px; */
    border:none;
    margin-top:20px;
    cursor:pointer;

}

/* Styles the submit hover */   
.button:hover {
    color:#fff;
    background-color: #ee2b7b;
    opacity:0.8;
}



/*--------------------------------------------------------*/  


















/*= FOOTER 
--------------------------------------------------------*/

#copyright  { 
color: #ee2b7b; 
font-family:"Source Sans Pro";  
font-size: 12px; 
margin: 100px 0 100px; 
text-align: center;  }
#copyright  a { text-decoration: underline; color: #cccccc;  }


Unknown type name ucontext64_t


Unknown type name 'ucontext64_t'; did you mean 'ucontext_t'?

What is the cause of this compilation error? Points to this code:

#ifdef __arm64__
    #define UC_MCONTEXT uc_mcontext64
    typedef ucontext64_t SignalUserContext;
#else
    #define UC_MCONTEXT uc_mcontext
    typedef ucontext_t SignalUserContext;
#endif

enter image description here

This code compiles in 1 of my projects, but it does not in the other. Both projects are linking to the same libraries. Anyone can help pointing to the build or other settings, which may affect that?


Parse PFFile download order iOS


I'm storing 5 PFFiles in an array and using getDataInBackgroundWithBlock to download those files from Parse.

The problem is the order at which they appear in the table view cells is different every time, presumably because the files are download at different speeds due to the different file sizes.

for (PFFile *imageFile in self.imageFiles) {
  [imageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
    if (!error) {
      UIImage *avatar = [UIImage imageWithData:imageData];
      [self.avatars addObject:avatar];
      cell.userImageView.image = self.avatars[indexPath.row];
    }
  }];
}

The self.imageFiles array is in the correct order. How do I ensure that the images downloaded are added to the self.avatars array in the same order as the self.imageFiles?


How to open Reminder Event Default screen using our app


I am creating a app where i can set the reminder based on Location and date.Apple has already given the UI if you are using Reminder which has both option.Can any one help me out that how can i open that Create event screen.Create Event either based on location or based on date


How to parse a RSS feed using NSXMLParser with variables on the feed address by pressing a button in a UIAlertController Alert in Swift?


I have been trying to integrate a Pinboard bookmarks view (by parsing an RSS Feed and displaying it in a TableView) in my browser app, and I'm encountering a few issues. You can see my previous questions here and here. I'm trying to use the variables I collected from my user in the Alert, to get the user's secret RSS feed token. However when I run the app, it causes a crash with a error of "EXC_BAD_INSTRUCTION" with the following console output:

fatal error: unexpectedly found nil while unwrapping an Optional value

I checked everything but I can't find a nil.

This is the code I'm using:

class SettingsTableViewController: UITableViewController, MFMailComposeViewControllerDelegate, NSXMLParserDelegate {

var _pinboardUsername: String?
var _pinboardAPIToken: String?

var parser: NSXMLParser = NSXMLParser()
var bookmarks: [Bookmark] = []
var pinboardSecret: String = String()
var eName: String = String()

...

    @IBAction func pinboardUserDetailsRequestAlert(sender: AnyObject) {
    //Create the AlertController
    var pinboardUsernameField :UITextField?
    var pinboardAPITokenField :UITextField?
    let pinboardUserDetailsSheetController: UIAlertController = UIAlertController(title: "Pinboard Details", message: "Please enter your Pinboard Username and API Token to access your bookmarks", preferredStyle: .Alert)
    //Add a text field
    pinboardUserDetailsSheetController.addTextFieldWithConfigurationHandler({(usernameField: UITextField!) in
        usernameField.placeholder = "Username"
        usernameField.text = self._pinboardUsername
        var parent = self.presentingViewController as! ViewController
        pinboardUsernameField = usernameField

    })
    pinboardUserDetailsSheetController.addTextFieldWithConfigurationHandler({(apiTokenField: UITextField!) in
        apiTokenField.placeholder = "API Token"
        apiTokenField.text = self._pinboardAPIToken
        var parent = self.presentingViewController as! ViewController
        pinboardAPITokenField = apiTokenField

    })
    pinboardUserDetailsSheetController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
    pinboardUserDetailsSheetController.addAction(UIAlertAction(title: "Done", style: .Default, handler: { (action) -> Void in
        // Now do whatever you want with inputTextField (remember to unwrap the optional)
        var valueUser = pinboardUsernameField?.text
        NSUserDefaults.standardUserDefaults().setValue(valueUser, forKey: AppDefaultKeys.PinboardUsername.rawValue)
        var valueAPI = pinboardAPITokenField?.text
        NSUserDefaults.standardUserDefaults().setValue(valueAPI, forKey: AppDefaultKeys.PinboardAPIToken.rawValue)
        let url:NSURL = NSURL(string: "http://ift.tt/1Otda4l")!
        self.parser = NSXMLParser(contentsOfURL: url)!
        self.parser.delegate = self
        self.parser.parse()

        func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) {
            self.eName = elementName
            if elementName == "result" {
                self.pinboardSecret = String()
                NSUserDefaults.standardUserDefaults().setValue(self.pinboardSecret, forKey: AppDefaultKeys.PinboardSecret.rawValue)
            }
        }
    }))
    self.presentViewController(pinboardUserDetailsSheetController, animated: true, completion: nil)   
}

The error is in the let url line of the parser function.

What am I doing wrong?

Thanks,

PastaCoder


How To Add Launch Screen File in Xcode for iPhone 6 Optimization?


I'd like to know how to add a Launch File in Xcode for iPhone 6 optimization?

On Xcode, when you click on NEW -> File -> User Interface -> Launch Screen a xib file is created in project. My question is how to "fill the blanks" and make that file (xib) useful for iPhone 6 optimization?

Apple requires it for iPhone 6 optimizations: iPhone 6 optimization Launch Images

Apple says,

"You use a launch XIB or storyboard file to indicate that your app runs on iPhone 6 Plus or iPhone 6."

Here's another reference of what I am talking about: Xcode: Using a Launch Image File

How to create that XIB / Storyboard to indicate that my app runs on iPhone 6 / 6+? Thanks in advance!


Unable To Get UIImage to Match Custom ImagePickerController Preview


I am building an iOS app that is to have a full screen ImagePickerController, with the resulting image that is captured to be the same that is shown in the ImagePickerController View. This is my current relevant code:

To create and transform the ImagePickerController:

    self.imagePicker = [[UIImagePickerController alloc] init];
self.imagePicker.delegate = self;


CGSize screenSize = [[UIScreen mainScreen] bounds].size;

// set the aspect ratio of the camera
float heightRatio = 4.0f / 3.0f;
// calculate the height of the camera based on the screen width
float cameraHeight = floorf(screenSize.width * heightRatio);
// calculate the ratio that the camera height needs to be scaled by
float scale = ceilf((screenSize.height / cameraHeight) * 10.0) / 10.0;

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;


    self.imagePicker.showsCameraControls = NO;
    [self.imagePicker setCameraOverlayView:cameraView];

    // move the controller to the center of the screen
    self.imagePicker.cameraViewTransform = CGAffineTransformMakeTranslation(0, (screenSize.height - cameraHeight) / 2.0);
    // concatenate the scale transform
    self.imagePicker.cameraViewTransform = CGAffineTransformScale(self.imagePicker.cameraViewTransform, scale, scale);
}

Once the image captured, here is the code I am using to redraw the captured image to match the Preview:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
 self.image = [info objectForKey:UIImagePickerControllerOriginalImage];
 self.image = [self croppedImage:self.image];

- (UIImage *) croppedImage: (UIImage *)image{

CGSize screenSize = [[UIScreen mainScreen] bounds].size;    
// set the aspect ratio of the camera
float heightRatio = 4.0f / 3.0f;
// calculate the height of the camera based on the screen width
float cameraHeight = floorf(screenSize.width * heightRatio);
// calculate the ratio that the camera height needs to be scaled by
float scale = ceilf((screenSize.height / cameraHeight) * 10.0) / 10.0;


CGSize originalImageSize = [image size];
CGSize newImageSize = CGSizeMake(floorf(originalImageSize.width / scale)* 3/4, floorf(originalImageSize.height / scale)* 3/4);

CGRect newImageRect = CGRectMake((originalImageSize.width - newImageSize.width)/2.0, (originalImageSize.height - newImageSize.height)/2.0, newImageSize.width, newImageSize.height);

return [image croppedImage:newImageRect];
}

So my problem is that my CroppedImage method is not calculating correctly, as the resulting image seems to be more "zoomed in" than needed. Not really sure what is wrong in the calculation.

Note - this app is to intended to scale properly on all iPhones - Portrait mode only. I am currently testing on iPhone 6.


Multiple buttons to single IBAction - How to change background of the previous tapped button?


I have a group of buttons a user can tap, almost like a calculator.

The app will collect a series of 2 buttons taps. This is to select a card from a deck. 1st tap would be Ace through King. 2nd tap would be a suit.

When the 1st button is tapped, it will change the background to yellow (the rank). When the 2nd button is tapped, it will save the 2 selections as a pair and append to a string (the suit).

Once the 2nd button is tapped, I want to change the 1st tapped button back to blue.

With all my buttons linked to a single IBAction 'buttonTapped', I can't get it to change the 1st button background to blue, when tapping the 2nd button. (I would even be OK with the 2nd button changing ALL buttons linked to this IBAction to blue)

@IBAction func buttonTapped(theButton: UIButton) {

    var buttonDump = theButton.titleLabel!.text!
    var firstChar = Array(buttonDump)[0]

    if firstChar == "♠️" || firstChar == "♥️" || firstChar == "♦️" || firstChar == "♣️" {
    // MUST BE THE 2nd TAP, SO LETS CHANGE THE 1st TAPPED BG BACK TO BLUE
        self.n2.text = buttonDump
        theButton.backgroundColor = UIColor.blueColor()

    } else {

        self.n1.text = buttonDump
        theButton.backgroundColor = UIColor.yellowColor()
    }

Thanks for supporting a Swift n00b, I'm working on it!

--UPDATE--

It makes sense that I need to define 'firstButton' in the class buttonTapped belongs to. I'm struggling here, I've attempted defining it as a UIButton so it is ready to receive the sender information.. What's the trick?

//What is the proper way to define a 'empty' UIButton before the value can be sent from the buttonTapped function?

firstButton: UIButton  // ???????? 
@IBAction func buttonTapped(theButton: UIButton) {

    var buttonDump = theButton.titleLabel!.text!
    var firstChar = Array(buttonDump)[0]

    if firstChar == "♠️" || firstChar == "♥️" || firstChar == "♦️" || firstChar == "♣️" {
        // MUST BE THE 2nd TAP, SO LETS CHANGE THE 1st TAPPED BG BACK TO BLUE
        self.n2.text = buttonDump

        // Change first button to blue
        self.firstButton.backgroundColor = UIColor.blueColor()
    } else {
        self.n1.text = buttonDump

        // Keep reference to first button
        self.firstButton = theButton
        self.firstButton.backgroundColor = UIColor.yellowColor()
    }


Navigation bar titleView alignment


I want my navigation bar to show two things in the middle. One them is going to be List name, and the other one will be name of users. User names will be placed under list name. What i have done so far is, i created two label and one superview programatically and set the titleView of navigationItem.

override func viewDidLoad() {
        super.viewDidLoad()
        var rectForView = CGRect(x: 0, y: 0, width: 190, height: 176)
        var viewForTitle = UIView(frame: rectForView)

        var rectForNameLabel = CGRect(x: 0, y: 63, width: 190, height: 30)
        var listNameLabel = UILabel(frame: rectForNameLabel)
        listNameLabel.text = "Name of the List...."
        listNameLabel.textAlignment = NSTextAlignment.Center
        listNameLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 15)

        var rectForListLabel = CGRect(x: 0, y: 93, width: 190, height: 20)
        var usersOfListLabel = UILabel(frame: rectForListLabel)
        usersOfListLabel.text = "some Users...."
        usersOfListLabel.textAlignment = NSTextAlignment.Center
        usersOfListLabel.font = UIFont(name: "HelveticaNeue", size: 10)

        viewForTitle.addSubview(listNameLabel)
        viewForTitle.addSubview(usersOfListLabel)


        self.navigationItem.titleView = viewForTitle

The thing is, I'm picking width randomly, which leads to alignment problems in different devices. How to achieve middle alignment in my case? iphone 6

iphone 5


How do I add a view under the default views in the navigation bar?


I've read that article but it is not completed, also the approach which is described in the article uses some tricky things, founded on the class naming, like

[classNamesToReposition containsObject:NSStringFromClass([view class])]

It doesn't look good in the code.

I'm looking for a better approach to do that. I need to put some custom view under the default views of navigation bar. Like this:

enter image description here

How can I do that using the titleView property of the navigation bar?


Open one mobile application from another using sso mutual authentication


I have a need to integrate my android/iphone application with a third party vendor iphone/android application. We want end users to download only one application and authenticate them only once. Is this possible?


How to load data for next page using UIPageViewController


I got UIPageViewController working finally a few days ago. I am using different UITableViewControllers as the "pages". There is a slight problem that i have that i want to fix.

When i scroll, the view is empty until fetches the new data which i don't like. I would like the data to be loaded before scrolling so it goes swiftly. So the question is: If i can load the next page somehow before scrolling.

I thought of a way to "fix" this in an ugly way by calling the fetch function somewhere before and save the dictionary in NSUserDefaults so when the view loads for the first time the data is already "loaded" and can be used.

Any other ideas of how this can be done the "right" way?


Swift---- Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:]


Getting the error after tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell runs for the several time.
Here's thing.I've create a teacherArray that contains the data used for the cell.And it surely contains what I need.I used the storyboard to custom the cell and the tableview.And I've checked that the identifier for cell is set and I also customize the class for the tableview and the cell in the identity inspector.

Code:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

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

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

    cell.nameLabel.text = teacherArray[indexPath.row].name
    cell.schoolLabel.text = teacherArray[indexPath.row].school
    cell.experienceLabel.text = teacherArray[indexPath.row].experience
    cell.courseLabel.text = teacherArray[indexPath.row].course

    println(indexPath.row)
    println(cell)

    return cell
}

I've track the method, and it's after the console output the following information that the error happened

6 PAL.SearchCell: 0x7bf32310; baseClass = UITableViewCell; frame = (0 450; 320 75); autoresize = W; layer =

and the following is error message
2015-04-26 22:27:54.880 PAL[65213:6357947]
* Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:], /SourceCache/UIKit_Sim/UIKit-3318.93/UITableView.m:7344 2015-04-26 22:27:54.889 PAL[65213:6357947] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'

I have no idea what I have done wrong.Any idea?


How does Apptimize \ Optimizely work on iOS?


I'm trying to figure out a few things about the implementation going on "behind the scene" for manipulating UI elements on the fly, straight from the web console on Apptimize or Optimizely.

More specifically, I want to understand the following:

1) How does the client code (iOS) send the view hierarchy to the web-server in such a way that when you choose any UI element on the web dashboard it immediately shown on the iOS client?

I saw FLEX for example, and how it manage to get the view hierarchy, but I don't understand how the iphone client "knows" which view is picked in the web dashboard.

2) Moreover, in Apptimize I can choose any UI element from the web dashboard, change its text or color and it will immediately change in the app. Not only that, without adding any code, just by having the SDK.

The changes I make (text, background color, etc) will remain for all the future sessions of the app. How can this be implemented?

I'm guessing they are using some sort of reflection, but how can they get it to work for all users and for all future sessions? how does the client code find the right UI element? and how does it work on UITableViewCell?

3) Is it possible to detect every time a UIViewController is loaded? i.e. get a callback on each viewDidLoad? if so, how?

See some screenshots below:

enter image description here

enter image description here


I need to imitate the finger touch of the user using iOS Objective C


i want to let the user touch the screen and i take these touches size and location and provide him with an image "as if it" was his fingerprint but with almost the same shape and size of his finger

i implemented the touchesBegan Function and the touchesMoves Function as follows (both have the same code)

as it's shown below the touchSize is the size of the actual user touch to the screen and it holds the radius of the touch, then i created a circular shape using SKshapeNode and color and displayed it on screen

it colors the node where i touched but when i move a touch the size starts to get bigger and i can not get it to draw the shape of the finger

        -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins*/

for (UITouch *touch in touches) {
    CGPoint location = [touch locationInNode:self];
CGFloat touchSize = [[touch valueForKey:@"pathMajorRadius"] floatValue];
        SKShapeNode *touchedLocation = [SKShapeNode shapeNodeWithCircleOfRadius:touchSize/4];
        touchedLocation.fillColor = [SKColor whiteColor];
        touchedLocation.position = location;
        [self addChild:touchedLocation];
}

}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

for (UITouch *touch in touches) {
    CGPoint location = [touch locationInNode:self]; 
CGFloat touchSize = [[touch valueForKey:@"pathMajorRadius"] floatValue];
        isScreenTouched = YES;
        SKShapeNode *touchedLocation = [SKShapeNode shapeNodeWithCircleOfRadius:touchSize/4];
        touchedLocation.fillColor = [SKColor whiteColor];
        touchedLocation.position = location;
        touchedLocation.name = @"AnamelPrint";
        [self addChild:touchedLocation];
    }
}


UIImagePickerController Rotating the Image in Swift


I am using UIImagePickerController to have the user of my app to take a photo or use the camera roll. When I tested the use camera option the image always rotates. But that never happens when I try to use the camera roll. This is the code I am using for the UIImagePickerController.

func photoLibary() {
    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    imagePicker.mediaTypes = [kUTTypeImage as NSString]
    imagePicker.allowsEditing = false

    self.view?.window?.rootViewController?.presentViewController(imagePicker, animated: true, completion: nil)
}

func camera() {
    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
    imagePicker.mediaTypes = [kUTTypeImage as NSString]
    imagePicker.allowsEditing = false

    self.view?.window?.rootViewController?.presentViewController(imagePicker, animated: true, completion: nil)
}

func choosePhoto() {

    let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)

    actionSheet.addAction(UIAlertAction(title: "Take Photo", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
        self.camera()
    }))

    actionSheet.addAction(UIAlertAction(title: "Camera Roll", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
        self.photoLibary()
    }))

    actionSheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))

    self.self.view!.window!.rootViewController!.presentViewController(actionSheet, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
    let image:UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
    image.texture = SKTexture(image: image)
    picker.dismissViewControllerAnimated(true, completion: nil)

}


Using segue inside custom cell TableViewController


Good afternoon,

I'm trying to create three segues inside my TableViewController in a custom cell and currently it's not working because I can't send the correct "username" throught the second and the third segue.

The second and the third segue are triggered when the user press the UIImageView and a UILabel (which are connected to a TapGestureRecognizer), and in those two segues I have the problem, because the "username" is not updated (it's always the same, the first one in my TableViewController).

What is wrong with my code? I'm going to post some screenshots of my StoryBoard because I don't know where is something wrong...

Here you are my Segue code (the first one is working fine):

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    NSIndexPath *myIndexPath = [self.tableView indexPathForSelectedRow];

    NSLog(@"RecipeName ==> %@", [[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:@"username"]);

    if ([[segue identifier] isEqualToString:@"ShowCarDetails"])
    {
        CarDetailViewController *detailViewController = [segue destinationViewController];

        detailViewController.carDetailModel = [[NSArray alloc]
                                               initWithObjects:
                                               [[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:@"date"],
                                               [[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:@"id"],
                                               [[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:@"imagen"],
                                               nil];
    }

    if ([segue.identifier isEqualToString:@"segueprofile"]) {

        OtherProfileUserViewController *destViewController = [segue destinationViewController];

        destViewController.recipeName = [[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:@"username"];
    }

    if ([[segue identifier] isEqualToString:@"segueprofile2"])
    {
        OtherProfileUserViewController *destViewController = [segue destinationViewController];

        destViewController.recipeName = [[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:@"username"];
    }
}

Here you are my screenshots from my StoryBoard:

http://ift.tt/1dgnz2r

Thanks in advance.


How do I resolve Bootstrap checkbox layout issue for iPhone


I have set up a screen layout using Bootstrap, and for most form factors, everything looks great, but with smaller iPhone sizes in portrait mode, my checkbox labels are mis-aligned. I am using labels to wrap the checkboxes so that the clickable target is much larger.

The html is as follows:

 <div class="row">
        <div class="col-lg-2 col-xs-12">
            <label>Endorsements</label><label class="required" ng-hide="row.hasNoEndorsements != undefined">*</label>
        </div>
        <div class="col-lg-3 col-xs-12">
            <label class="form-control"><input type="checkbox" value='false' title="None" ng-model="row.hasNoEndorsements" ng-click="vm.endorsementClick(row, true)"> None</label>
        </div>
        <div class="col-lg-3 col-xs-12">
            <label class="form-control"><input type="checkbox" value='true' title="Tanker" ng-model="row.isTanker" ng-click="vm.endorsementClick(row, false)"> Tanker</label>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-2 col-xs-12">
        </div>
        <div class="col-lg-3 col-xs-12">
            <label class="form-control"><input type="checkbox" value='true' title="Doubles/Tripples" ng-model="row.isDoubleTriple" ng-change="vm.endorsementClick(row, false)">Double/Tripple</label>
        </div>
        <div class="col-lg-3 col-xs-12">
            <label class="form-control"><input type="checkbox" value='true' title="HazMat" ng-model="row.isHazmat" ng-change="vm.endorsementClick(row, false)"> HazMat</label>
        </div>
        <div class="col-lg-3 col-xs-12">
        </div>
        <div class="col-lg-2 hidden-xs hidden-sm">
            <button value="Remove License" title="Remove License" ng-click="vm.licenseRemove(row)" class="btn btn-info">Remove License</button>
        </div>
    </div>

Checkbox labels misaligned

In all other form factors the display is as expected.enter image description here


WatchKit access to iPhone Microphone


AppleWatch is not authorized to access the microphone, but on Apple forums I read that the WhachKit can access to the microphone of parent app. How?


Do text conversations have a certain data type in iOS?


I am looking to have an iPhone app extension that actions on text conversations. I know text messages are saved in a sqlite database in iPhone but I was wondering if they follow a certain data type in iPhone when displaying.


Poor Performance with multiple UICollectionViewCells in one CollectionVIew


I have a CollectionView with multiple cell types. When scrolling between different cell types performance can get very laggy. I'm not exactly sure how to fix it. Here's my cellForItemAtIndexPath:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

if cellType == "imageCell" {

            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("iCell", forIndexPath: indexPath) as! ImageCell

            //do things for cell

            return cell

        }else if cellType == "mapCell" {

            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("mCell", forIndexPath: indexPath) as! MapCollectionViewCell

            //do things for cell

            return cell

        }else if cellType == "pCell" {

            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("pCell", forIndexPath: indexPath) as! PCell

            //do things for cell

            return cell

        }else if cellType == "detailCell" {

            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("fCell", forIndexPath: indexPath) as! DetailCell

            //do things for cell

            return cell

        }else{
            return UICollectionViewCell()
        }}


How to change aspect ratio of a UIView


I have a custom UIView which uses autolayout programatically to set the size of the frame. For this purpose, I set a constraint on the width property of the view to be equal to that of the superview and then a constraint of the aspect ratio to be some hard coded value

//width constraint
NSLayoutConstraint *widhtConstraint=[NSLayoutConstraint constraintWithItem:entryView
                                                                 attribute:NSLayoutAttributeWidth
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:scrollView
                                                                 attribute:NSLayoutAttributeWidth
                                                                multiplier:1.0f
                                                                  constant:8.0f];

[scrollView addConstraint:widhtConstraint];

//aspect ratio constraint
NSLayoutConstraint *aspectRatioConstraint=[NSLayoutConstraint constraintWithItem:entryView
                                                                       attribute:NSLayoutAttributeWidth
                                                                       relatedBy:NSLayoutRelationEqual
                                                                          toItem:entryView
                                                                       attribute:NSLayoutAttributeHeight
                                                                      multiplier:80.0/27.0//aspect ratio same as formula view
                                                                        constant:0.0f];

[scrollView addConstraint:aspectRatioConstraint];

Please refer image:

Constraint setup

I wish to change the aspect ratio of this frame on touch of a button(View More) by increasing its height and then later resize it back to original on touching the same button.Additionally how do I figure out the total height of the view governed by all its subviews such that each subview is visible without clipping.(Basically the standard collapse feature)


Some explanations for iOS xcasset catalogs required


I am completely new to iOS development. I want to make a small game with the Sprite-Kit framework and I am already stuck at the xcasset catalog.

Say I have a 320x320 pixel image for my iPhone 4s that features a resolution of 960x480 pixels. I put this to "iPhone 2x" in the xcasset catalog, right (cp. following image) ?

enter image description here

Now, do I need for the "iPhone 1x" a 160x160 and for the "iPhone 3x" a 640x640 version of the image? What about the iPad ? What does "iPad 1x" and "iPad 2x" exactly mean in terms of pixels? Is "iPad 1x" also 320x320 and "iPad 2x" 640x640 in my example ?


Hello, am new to ios. can anyone help me how to add local notification using datepicker in ios


can anyone please help me in coding for local notification using datepicker object in ios. Thanku


How to rotate a Direction Arrow to particular location for (swift)


my app rotate an image to particular location but it's not work and the arrow rotate to the north , i want the arrow rotate to the particular location

please i want swift not objective-c and i check to another questions but all questions here for objective-c and i try to make the same this questions on the link enter link description here it's doesn't work

class ViewController: UIViewController,CLLocationManagerDelegate{

var direction = []
var coordinate = CLLocationCoordinate2D()
var radiansValue = CGFloat()
var angle = CGFloat()
var locationManager = CLLocationManager()
var arrowImageView : UIImageView? = UIImageView()
var latitudeOfTargetedPoint = CLLocationDegrees()
var longitudeOfTargetedPoint = CLLocationDegrees()

func DegreesToRadians (value: Double) -> CGFloat {
    return CGFloat(value * M_PI / 180.0)
}


func RadiansToDegrees (value: Double) -> CGFloat {
    return CGFloat(value * 180.0 / M_PI)

}

override func viewDidLoad() {
    super.viewDidLoad()

    arrowImageView!.frame = CGRect(x: 100, y: 200, width: 100, height: 100)
    arrowImageView!.image = UIImage(named: "arrow.png")
    view.addSubview(arrowImageView!)

    if CLLocationManager.locationServicesEnabled() {

        println("CLLocationManager.locationServicesEnabled")

        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = 100.0;

        self.locationManager.startUpdatingLocation()
        self.locationManager.startUpdatingHeading()

        latitudeOfTargetedPoint = 48.021199
        longitudeOfTargetedPoint = 29.264888

        var coordinate = CLLocationCoordinate2DMake(latitudeOfTargetedPoint, longitudeOfTargetedPoint)

        var latDelta:CLLocationDegrees = 0.01
        var lonDelta:CLLocationDegrees = 0.01

        var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
        var region:MKCoordinateRegion = MKCoordinateRegionMake(coordinate, span)


        println(calculateAngle)
    }

}//29.264888, 48.021199

// Caculate the angle between the north and the direction to observed geo-location

func calculateAngle (userlocation: CLLocation) -> CGFloat{

    var userLocationLatitude = DegreesToRadians(userlocation.coordinate.latitude)
    var userLocationLongitude = DegreesToRadians(userlocation.coordinate.longitude)

    var targetedPointLatitude = DegreesToRadians(latitudeOfTargetedPoint);
    var targetedPointLongitude = DegreesToRadians(longitudeOfTargetedPoint)

    var longitudeDifference = targetedPointLongitude - userLocationLongitude
    var y = sin(longitudeDifference) * cos(targetedPointLatitude)
    var x = cos(userLocationLatitude) * sin(targetedPointLatitude) - sin(userLocationLatitude) * cos(targetedPointLatitude) * cos(longitudeDifference);

    var radiansValue = atan2(y, x)

    if radiansValue < 0.0 {
        var temFloast = Float(radiansValue)

        temFloast = temFloast + Float(2 * M_PI);
        radiansValue = CGFloat(temFloast)

        //radiansValue += 2*M_PI;

                }

    return radiansValue

}

func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {

    self.angle = calculateAngle(oldLocation!)

     }


func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    println(error.localizedDescription)
}

func locationManager(manager: CLLocationManager!, didUpdateHeading newHeading: CLHeading!) {


    var  direction = newHeading.magneticHeading
    angle = RadiansToDegrees



    if (direction > 180){
        direction = 360 - direction;
    }else{
        direction = 0 - direction;
    }

    //    Rotate the arrow image
    if arrowImageView != nil {

        UIView.animateWithDuration(1.0, animations: { () -> Void in
            self.arrowImageView!.transform = CGAffineTransformMakeRotation(self.DegreesToRadians(direction) + self.angle)
        })

    }

}


}


iOS swift - how to draw an ellipse with touch event


currently I am trying to port my old windows phone app to iphone. The UI looks like this:

enter image description here

I want to know how to do the following:

  1. Draw a solid ellipse on a specific position, e.g. at position x = 0, y = 0;
  2. The ellipse change its color upon touch;
  3. Touch another position on screen, the ellipse animated to move to the specific position.

I tried several tutorial on how to override drawRect in UIView, but couldn't get it work, can anyone help provide a simple sample?

Thanks a lot!


iOS softkeyboard scrolls page down


I'm having a bit of a play with jquery.terminal inside of a jquery dialog box. The intent is to create a terminal for mobile devices. This works great on Android, but for some reason when a page visitor is about to enter a command on an iPhone (iOS device) the viewport size adjusts to the fact that there is a keyboard, and the page scrolls down. This is very frustrating.

Does anyone have an idea that could possibly fix this? I'd like the page to remain where it is when typing. I think I need an extra bit of JavaScript to readjust the page when the keyboard is open. I've searched across StackOverflow and I see some similar discussions, but nothing works for me.

Any help is greatly appreciated.

My code is spread across several files and can all be found here as follows: http://ift.tt/1Jrl4I3

The HTML is below:

<!DOCTYPE HTML>
<html xmlns="http://ift.tt/lH0Osb">
  <head>
    <meta charset="UTF-8" />
    <title>Test</title>
    <meta name="description" content="Test">
    <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
    <script src="http://ift.tt/1dLCJcb"></script>
    <script src="http://ift.tt/1NKbGQl"></script>
    <script src="jquery.mousewheel-min.js"></script>
    <script src="jquery.terminal-0.8.8.js"></script>
    <link href="jquery.terminal.css" rel="stylesheet"/>
    <style type="text/css">
    body {
        background-image: url(background.png);
        background-size: contain;
        background-color: #000000;
    }
    </style>
  </head>

  <script>
  $(function() {
    $( "#test" ).dialog({
        dialogClass: "no-dialog-padding",
        height: $(window).height(),
        width: $(window).width(),
        resizable: false,
        title: false,
        position: 'top+10%',
    });
  });
  $(window).resize(function () {
    $('.ui-dialog').css({
            'width': $(window).width(),
            'height': $(window).height(),
            'left': '0px',
            'top':'0px'
    });
  }).resize();

  </script>

<div id="test">
  <script src="terminal.js"></script>
</div>


</body>

And JavaScript (for the Terminal):

jQuery(document).ready(function($) {
    var id = 1;
    var ua = navigator.userAgent.toLowerCase();
    var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
    $('#test').terminal(function(command, term) {
        if (command.match(/test/i)){
            term.echo("\nOMG DID THAT REALLY JUST HAPPEN?\n");
        } else if (command == 'CLEAR') {
            term.clear();
        } else if (command.match(/^\s*exit\s*$/i)) {
            if (term.level() == 1 && term.token() || term.level() > 1) {
                term.pop();
            }
        } else {
            term.echo("\nERROR: UNKNOWN COMMAND\n");
        }

    }, {
        greetings: "ANDROID TESTER\n"+
                   "TYPE 'TEST' AND HOLD YOUR BREATH ...\n",

        altinput: isAndroid,

        onBlur: function() {
            // prevent loosing focus
            return false;
        }


    });
});


How to open facebook page's post using iOS url schema


URL schema for open a facebook post in a facebook page for iOS using ObjC

for example

http://ift.tt/1Gkm7TP


Linphone App ipa file getting invalid Signature error while uploading to itunes


We were facing an issue from 4 days, but couldn't slove the issue. Can any one help me we appreciate them alot. while uploading Linphone-iOS ipa file(64-bit source Code) to iTunes through Application loader. we using mac version 10.10.3, xcode version 6.1.1. Below is the error we were getting while uploading through Application loader. can you suggest me how we can able to slove the issue. Thanks in advance.

"Invalid Signature. Code object is not signed at all. The binary at path [http://ift.tt/1DoFfOs] contains an invalid signature. Make sure you have signed your application with a distribution certificate, not an ad hoc certificate or a development certificate. Verify that the code signing settings in Xcode are correct at the target level (which override any values at the project level). Additionally, make sure the bundle you are uploading was built using a Release target in Xcode, not a Simulator target. If you are certain your code signing settings are correct, choose "Clean All" in Xcode, delete the "build" directory in the Finder, and rebuild your release target. For more information, please consult http://ift.tt/1z7yJRa”]