samedi 25 avril 2015

Need help interpreting a crash log from QuincyKit


I recently added QuincyKit (a crash log reporter that sits on top of PLCrashReporter) into an app and I received a crash log that I'm having trouble interpreting.

The crash log seems to be inconsistent - it says it was thread 0 that crashed, but the "Last Exception Backtrace" doesn't match with the thread 0 callstack. The last exception points to a table method, but thread 0 callstack indicates an abort occurred during the Quincy manager initialization.

Moreover, the "Last Exception Backtrace" doesn't seem to make much sense taken on it's own - the "canEditRowAtIndexPath" method doesn't even include a call to "removeObjectAtIndex" at all (see below for the method).

Can anyone shed any light onto whether or not I should be paying attention to the "Last Exception Backtrace" or is that a red herring, and I should really be looking into why PLCrashReporter aborted during start up?

Many thanks

Crash log excerpt:

Exception Type:  SIGABRT
Exception Codes: #0 at 0x38362df0
Crashed Thread:  0

Application Specific Information:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 7 beyond bounds [0 .. 6]'

Last Exception Backtrace:
0   CoreFoundation                       0x29920fef <redacted> + 126
1   libobjc.A.dylib                      0x37d0cc8b objc_exception_throw + 38
2   CoreFoundation                       0x29833821 -[__NSArrayM removeObjectAtIndex:] + 0
3   DART                                 0x000906b3 -[DeliveryComplete tableView:canEditRowAtIndexPath:] + 262
4   UIKit                                0x2d0a3c25 -[UITableView _canEditRowAtIndexPath:] + 60
5   UIKit                                0x2d0a3a7f -[UITableView _setupCell:forEditing:atIndexPath:animated:updateSeparators:] + 130
6   UIKit                                0x2d0a1179 <redacted> + 2320
7   UIKit                                0x2cf82a31 +[UIView performWithoutAnimation:] + 72
8   UIKit                                0x2d0a0861 -[UITableView _configureCellForDisplay:forIndexPath:] + 336
9   UIKit                                0x2d246383 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 498
10  UIKit                                0x2d24642f -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 54
11  UIKit                                0x2d23b013 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2258
12  UIKit                                0x2d049657 -[UITableView layoutSubviews] + 186
13  UIKit                                0x2cf73023 -[UIView layoutSublayersOfLayer:] + 546
14  QuartzCore                           0x2c993d99 -[CALayer layoutSublayers] + 128
15  QuartzCore                           0x2c98f5cd <redacted> + 360
16  QuartzCore                           0x2c98f455 <redacted> + 16
17  QuartzCore                           0x2c98edf1 <redacted> + 224
18  QuartzCore                           0x2c98ebdf <redacted> + 434
19  UIKit                                0x2cf6b23b <redacted> + 126
20  CoreFoundation                       0x298e6fed <redacted> + 20
21  CoreFoundation                       0x298e46ab <redacted> + 278
22  CoreFoundation                       0x298e4ab3 <redacted> + 914
23  CoreFoundation                       0x29831201 CFRunLoopRunSpecific + 476
24  CoreFoundation                       0x29831013 CFRunLoopRunInMode + 106
25  GraphicsServices                     0x3100d201 GSEventRunModal + 136
26  UIKit                                0x2cfd5a59 UIApplicationMain + 1440
27  DART                                 0x00015491 _mh_execute_header + 25745
28  libdyld.dylib                        0x38298aaf <redacted> + 2

Thread 0 Crashed:
0   libsystem_kernel.dylib               0x38362df0 __pthread_kill + 8
1   libsystem_c.dylib                    0x382fe909 abort + 76
2   DART                                 0x00122dd7 -[PLCrashReporter enableCrashReporterAndReturnError:] + 1294
3   CoreFoundation                       0x2992131f <redacted> + 630
4   libobjc.A.dylib                      0x37d0cf13 <redacted> + 174
5   libc++abi.dylib                      0x37643de3 <redacted> + 78
6   libc++abi.dylib                      0x376438af __cxa_rethrow + 102
7   libobjc.A.dylib                      0x37d0cdd3 objc_exception_rethrow + 42
8   CoreFoundation                       0x2983129d CFRunLoopRunSpecific + 632
9   CoreFoundation                       0x29831013 CFRunLoopRunInMode + 106
10  GraphicsServices                     0x3100d201 GSEventRunModal + 136
11  UIKit                                0x2cfd5a59 UIApplicationMain + 1440
12  DART                                 0x00015491 _mh_execute_header + 25745
13  libdyld.dylib                        0x38298aaf <redacted> + 2

"canEditRowAtIndexPath" method:

-(BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == SIGNER_TABLE_TAG_VALUE)
    {

        RouteStopData *currentStop = [CurrentRoute singleton].selectedStop;
        NSArray *signers = [currentStop signerNamesForStop];

        if (indexPath.row >= [signers count])
        {
            return NO;
        }

        if ([[signers objectAtIndex:indexPath.row] isEqualToString:DARK_DROP_SIGNER_STRING] ||
            [[signers objectAtIndex:indexPath.row] isEqualToString:PAPER_INVOICE_SIGNER_STRING] ||
            [[signers objectAtIndex:indexPath.row] isEqualToString:ADD_NEW_SIGNER_STRING]
            )
        {
            return NO;
        }

        return YES;
    }

    return NO;
}


StoreKit.framework deleted from Library directory


Is there any change to get StoreKit.framework from iOS SDK 8.3 if I accidentally deleted it (without downloading Xcode again)?

It was linked to one of my projects, at some point I needed to delete it but instead of pressing "Remove reference", I pressed "Move to trash" and also "Emptied trash" after that...so now I'm unable to get it back.

Thanks, Alin


UIBezierPath Subclass Initaliser


I'm trying to create a subclass of UIBezierPath to add some properties that are useful to me.

class MyUIBezierPath : UIBezierPath {
   var selectedForLazo : Bool! = false

   override init(){
       super.init()
   }

   /* This doesn't work */
   init(rect: CGRect){
       super.init(rect: rect)
   }

   /* This doesn't work */
   init(roundedRect: CGRect, cornerRadius: CGFloat) {
       super.init(roundedRect: roundedRect, cornerRadius: cornerRadius)
   }

   required init(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
}

I don't understand how to call a designated initializer without losing information ( e.g call every time super.init() )

Can you help me please?


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?


Uploading a file from AVCapture using AFNetworking


I have a video that is captured with AVCapture, and I'm trying to upload with AFNetworking with Swift.

Code:

let manager = AFHTTPRequestOperationManager()
let url = "http://localhost/test/upload.php"
var fileURL = NSURL.fileURLWithPath(string: ViewControllerVideoPath)
var params = [
    "familyId":locationd,
    "contentBody" : "Some body content for the test application",
    "name" : "the name/title",
    "typeOfContent":"photo"
]

manager.POST( url, parameters: params,
    constructingBodyWithBlock: { (data: AFMultipartFormData!) in
        println("")
        var res = data.appendPartWithFileURL(fileURL, name: "fileToUpload", error: nil)
        println("was file added properly to the body? \(res)")
    },
    success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
        println("Yes thies was a success")
    },
    failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
        println("We got an error here.. \(error.localizedDescription)")
})

The code above fails, note that ViewControllerVideoPath is a string containing the location of the video which is: "/private/var/mobile/Containers/Data/Application/1110EE7A-7572-4092-8045-6EEE1B62949/tmp/movie.mov" using print line.... The code above works when Im uploading a file included in the directory and using:

 var fileURL = NSURL.fileURLWithPath(NSBundle.mainBundle().pathForResource("test_1", ofType: "mov")!)

So definitely my PHP code is fine, and the problem lies with uploading that file saved on the device, what am I doing wrong here?


ReactiveCocoa Issue


I'm attempting to use ReactiveCocoa in my project to handle the population of a UITableView.

When I load the data if none is available, I want to set the hidden property of tableView.backgroundView to false. Here's what I have so far:

func loadData() {
    let dataSource = tableView.dataSource as! BlockedTableViewDataSource
    let load = dataSource.load # RACSignal

    load.map {
        return ($0 as! [AnyObject]).count > 0
    }.startWith(true).distinctUntilChanged().setKeyPath("hidden", onObject: tableView.backgroundView!)

    load.subscribeError({ error in
        println(error)
    }, completed: {
        self.tableView.reloadData()
        self.refreshControl?.endRefreshing()
    })
}

This however errors out saying that I need to wait for the network request to finish. I'm using Parse to fetch the data but I'm thinking that my ReactiveCocoa code just isn't set up correctly and is causing this error. If I comment out the load.map... portion the table populates as expected.

How would one going about implementing this in the "Reactive Way"?


character jumps more than anticipated?


my problem is that when i jump at the start of my game it jumps three times when I only want to jump 2 times. What the code does is at the start a bool startgame is set to false and when clicked start moving the shape and starts the animation of dan, the character of my game. In the update method whenever the shape and dan touch the isjumping boolean variable is set to false so that when you click, dan jumps and then sets the didjumponce boolean to true so that it can jump for a second time. but for some reason at the start of the game it allows dan to jump three times. i tried setting a touch counter(timestapped) to 0 and every time there is a tap it adds on 1 so that when it checks if you can jump a second time is doesn't allow it. but it still does. thanks :)

@implementation GameScene
bool isJumping;
bool isPlaying;
bool didJumpOnce;
bool startGame = false;
int timesTapped = 0;

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

    timesTapped++;

    // checks to see if the game has started, if it hasn't, starts dan's animation
    if (startGame == false)
    {
        startGame = true;
        [self dansAnimation];
    }
    else if (isJumping == false)
    {
        isJumping = true;
        didJumpOnce = true;

        dan.physicsBody.velocity = CGVectorMake(0, 0);
        [dan.physicsBody applyImpulse: CGVectorMake(0, 55)];
    }
    else if (didJumpOnce == true && timesTapped != 2)
    {
       didJumpOnce = false;

        dan.physicsBody.velocity = CGVectorMake(0, 0);
        [dan.physicsBody applyImpulse: CGVectorMake(0, 55)];
    }
}

-(void)update:(CFTimeInterval)currentTime
{
    /* Called before each frame is rendered */

   if (startGame == true)
   {
        shape.position = CGPointMake(shape.position.x - 7, shape.position.y);
   }

   if (CGRectIntersectsRect(dan.frame, shape.frame))
   {
        isJumping = false;
   }
}
@end


iOS PFQueryTableViewController with UISearchController in iOS8


Is there a way to get PFQueryTableViewController work with UISearchController in ios8. I manage to get results but soon as I try to paginate or reload table it crashes because of number of rows


RegEx negative-lookahead and behind to find characters not embedded within a wrapper


I would like to match strings/characters that are not surrounded by a well-defined string-wrapper. In this case the wrapper is '@L@' on the left of the string and '@R@' on the right of the string.

With the following string for example:

This is a @L@string@R@ and it's @L@good or ok@R@ to change characters in the next string

I would like to be able to search for (any number of characters) to change them on a case by case basis. For example:

  1. Searching for "in", would match twice - the word 'in', and the 'in' contained within the last word 'string'.
  2. Searching for a "g", should be found within the word 'change' and in the final word string (but not the first occurrence of string contained within the wrapper).

I'm somewhat familiar with how lookahead works in the sense that it identifies a match, and doesn't return the matching criteria as part of the identified match. Unfortunately, I can't get my head around how to do it.

I've also been playing with this at http://regexpal.com/ but can't seem to find anything that works. Examples I've found for iOS are problematic, so perhaps the javascript tester is a tiny bit different.

I took some guidance from a previous question I asked, which seemed to be almost the same but sufficiently different to mean I couldn't work out how to reuse it:

Replacing 'non-tagged' content in a web page

Any ideas?


Cant't take an object id from a parse object and use it in other sections of code


Ive spent countless hours trying to figure out why I can't seem to take the object id of an object that has been saved to parse and use it in other sections of my code. Yes I have searched and found topics about this on stack overflow and other websites and I have read the parse.com documentation but none of the answers will allow me to fix this issue. I am pretty new to coding and I am only familiar with swift at the moment. If you can help me figure this out I would more than appreciate your help.

I declare objectID as a string variable at the top of the code. Later when a send button is tapped I save the data to parse successfully and attempt to capture the datas objectId by passing the objectID variable to the saveToParse function as an inout. The project does not show any errors. The code builds and runs. NSLog(id) shows me the proper objectId that I want in the console. However it does not show anything when NSLog(self.objectID) is called outside of the function.

Like I said, I'm trying to use this objectId outside the function in other parts of the code, but it just doesn't want to save the objectId to my variable. I've tried many other methods and this is the closest I have got to making it work.

Im new at this so hope I've explained my situation clearly, if you need any more information to solve this don't hesitate to ask. Thanks for reading :)

var objectID:String = String() // declared at the top (underneath Class)

@IBAction func sendQuestionTapped(sender: UIButton) {

    // Send question and answers to Parse
        saveToParse(&objectID)



    // Save Question object ID

        NSLog(self.objectID)  // Test if objectID is still Question.objectId

    // Move to the results view controller with information
    performSegueWithIdentifier("toResultsSegue", sender: self)


}

func saveToParse(inout id:String) {

    var Question = PFObject(className:"Question")
    Question["question"] = questionToPass
    Question["answers"] = arrayToPass

    Question.saveInBackgroundWithBlock {
        (success: Bool, error: NSError?) -> Void in
        if (success) {
            // The object has been saved.
            dispatch_async(dispatch_get_main_queue()) {

                id = Question.objectId!
                NSLog(id)

            }

        }

        else {

            // There was a problem, check error.description
            if error != nil {

                NSLog(error!.localizedDescription)
            }
        }
    }
}


NSDateFormatter converting string to date in objective c


How to convert string to date in objective c?


Adding a library into a iOS project


I installed MumbleKit and I would like to use the library in a project. I tried following the instructions in the page, but just copying the MumbleKit icon in the new project does not make it appear in the target dependencies, while adding the whole project produces the familiar errors due to the obsolete syntax of the code used in the library. How do I add the library without having to compile everything together?

Thanks.


saving objects to parse


I'm still new to ios development but I have a good knowledge of the swift language, I'm trying now to learn how to save objects to Parse, after I created my app on parse and downloaded the xcode swift template from Parse and pasted the application id & cleint-key to the appDelegate.swift file and add save file code from Parse to the viewController file and tried to run the app, I got this error in appDelegate.swift : please check the link below to view the error: http://ift.tt/1GsJgGj

    PFPush.subscribeToChannelInBackground("", block: { (succeeded: Bool, error: NSError!) -> Void in
        if succeeded {
            println("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.");
        } else {
            println("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %@.", error)
        }
    })
}![enter image description here][2]


SDK V1.8 kinect gesture control


I am working on a project that if left hand is on the right side of the head and the right hand is higher than spine the the F3 key will go on etc.... What am i doing wrong, the code dosent read the ProcessControlGesture. I am new to this please help! How do i define IsMoveRightGestureActive

private void ProcessControlGesture(Joint head, Joint rightHand, Joint leftHand, Joint spine) { if (leftHand.Position.X > head.Position.X && rightHand.Position.Y > spine.Position.Y) { if (!isMoveRightGestureActive) { isMoveRightGestureActive = true; Console.WriteLine(" Move Left Gesture Regniized: MOVE LEFT"); System.Windows.Forms.SendKeys.SendWait("{F3}"); } } else { isMoveRightGestureActive = fasle; }

        if (rightHand.Position.X < head.Position.X && leftHand.Position.Y > spine.Position.Y)
        {
            if (!isMoveLeftGestureActive)
            {
                isMoveLeftGestureActive = true;
                Console.WriteLine(" Move Right Gesture Recognized: MOVE RIGHT");
                System.Windows.Forms.SendKeys.SendWait("{F1}");
            }
        }
        else
        {
            isMoveLeftGestureActive = false;
        }

        if (leftHand.Position.Y > head.Position.Y && rightHand.Position.Y > head.Position.Y)
        {
            if (!isStopGestureActive)
            {
                isStopGestureActive = true;
                Console.WriteLine("STOP");
                System.Windows.Forms.SendKeys.SendWait("{F5}");


UISegmentedControl tintColor


I'm having problems getting UISegmentedControl to show the desired tint color.

// AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // need red tint color in other views of the app
    [[UIView appearance] setTintColor:[UIColor redColor]];
    return YES;
}

// ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *items = @[@"Item 1", @"Item 2"];
    UISegmentedControl *control = [[UISegmentedControl alloc] initWithItems:items];
    // would like to have this control to have a green tint color
    control.tintColor = [UIColor greenColor];
    [self.view addSubview:control];
}

How to make UISegmentedControl use the green tint color?


xcode interface builder - view sticks to the mouse


For some reason I cannot get drag and drop any view right now. I can drag, but then the view just sticks to the mouse - cannot drop!:D

Happens on Xcode 6.3 (6D570), OS X Yosemite 10.10.3 (14D136), MBP15 mid2010.

I've restarted Xcode several times - no change. I guess it's a bug in this update?


iOS making a new project for an existing app


I'm remaking from scratch an app that was previously in Objective-C, to Swift. But I'm not really sure how can I make the new project be linked to the app that is already in iTunes Connect. What I mean to say is that I have a new project whose binary is supposed to be uploaded as the binary of the already registered app.

Besides using the same Bundle Identifier, what else do I need to do to achieve this?

PS: For some reason, the new project won't let me change the bundle identifier's last part: the old one was com.example.myproject while the new one is com.exmaple.MyProject (the new one has capital letters). When I click on the text box to change it to lower case, the MyProject color change to gray and I can't delete it


Objective C - Remove only UIButtons from superview


I am fairly new to objective-c and I have ran into an issue that I have had a hard time solving..

I am using ShinobiDataGrid and using their prepareCellForDisplay.

To get text to display I would do this:

if([cell.coordinate.column.title isEqualToString:@"Task"]){
            textCell.textField.textAlignment = NSTextAlignmentLeft;
            textCell.textField.text = cellDataObj.task;
        }

but for a particular cell, I am trying to add a custom button:

if([cell.coordinate.column.title isEqualToString:@"selected"]){


            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(0, 10 , 32, 32);



            if(cellDataObj.selected){

                [button setImage:[UIImage imageNamed:@"checked-box.png"] forState:UIControlStateNormal];

            }else{

                [button setImage:[UIImage imageNamed:@"unchecked-box.png"] forState:UIControlStateNormal];

            }

            button.tag = cell.coordinate.row.rowIndex;
            [button addTarget:self action:@selector(CheckBoxPressed:) forControlEvents:UIControlEventTouchUpInside];

            [cell addSubview:button];

            [button removeFromSuperview];

        }

and I first run the app, the checkbox appears. but when I reload my ShinobiDataGrid the checkbox appears again. I tried removing the button from the superview, but that didn't work...any suggestions ? When I reload my ShinobiDataGrid a 3rd time, the checkbox does not appear for a 3rd time, just adds another when I reload the ShinobiDataGrid the 2nd time. Here is the whole method:

- (void)shinobiDataGrid:(ShinobiDataGrid *)grid prepareCellForDisplay:(SDataGridCell *)cell
{

    SDataGridTextCell* textCell = (SDataGridTextCell*)cell;

    CellData *cellDataObj = [cellHolderDisplay objectAtIndex:cell.coordinate.row.rowIndex];

    textCell.textField.textAlignment = NSTextAlignmentCenter;

    if([cell.coordinate.column.title isEqualToString:@"selected"]){


        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 10 , 32, 32);



        if(cellDataObj.selected){

            [button setImage:[UIImage imageNamed:@"checked-box.png"] forState:UIControlStateNormal];

        }else{

            [button setImage:[UIImage imageNamed:@"unchecked-box.png"] forState:UIControlStateNormal];

        }

        button.tag = cell.coordinate.row.rowIndex;
        [button addTarget:self action:@selector(CheckBoxPressed:) forControlEvents:UIControlEventTouchUpInside];

        [cell addSubview:button];

        [button removeFromSuperview];

    }


    if([cell.coordinate.column.title isEqualToString:@"Task"]){
        textCell.textField.textAlignment = NSTextAlignmentLeft;
        textCell.textField.text = cellDataObj.task;
    }

    if([cell.coordinate.column.title isEqualToString:@"BLine. Start"]){
        textCell.textField.text = cellDataObj.baselineDate;
    }
}

Any suggestions ?

Here is the CheckBoxPressed method:

- (void)CheckBoxPressed:(UIButton *)sender
{
    CellData *cell = [cellHolder objectAtIndex:sender.tag];

    if([cell selected] == YES)
    {
        [[cell actualDate]setString:@""];
        [[cell finishedDate] setString:@""];
        [cell setSelected:NO];
    }
    else
    {
        if(([[cell actualDate] isEqualToString:@""]) && ([[cell finishedDate] isEqualToString:@""]))
        {
            [[cell actualDate]setString:[NSString stringWithFormat:@"%@ 8:00:00 AM",[self SetSpecialDateFormat:[NSDate date]]]];
            [[cell finishedDate]setString:[NSString stringWithFormat:@"%@ 4:00:00 PM",[self SetSpecialDateFormat:[NSDate date]]]];
        }
        //actual date not populated but finish date populated
        else if(([[cell actualDate]isEqualToString:@""]) && !([[cell finishedDate] isEqualToString:@""]))
        {
            [[cell actualDate]setString:[cell finishedDate]];
        }
        //finish date not populated but actual date populated
        else if(!([[cell actualDate] isEqualToString:@""]) && ([[cell finishedDate] isEqualToString:@""]))
        {
            [[cell finishedDate]setString:[cell actualDate]];
        }

        [cell setSelected:YES];

    }
    [self UpdateEdittedCells:cell];
    [self SetDisplayHolder];

    //refresh grid
    [gridReference reload];
}


Consequences of Changing CFBundleName? iOS 7 and iOS 8


The wrong app name is displayed in the Apple Watch app in the My Watch list. It shows the CFBundleName contents. Advice has been given in the Apple Developer forum to set the CFBundleName and the CFBundleDisplayName in all 3 apps (iPhone App, Watch App, Watch Extension). Changing the CFBundleDisplayName is not enough.

So, I am considering changing the CFBundleName. Our team has an existing app. I need to know what will happen if I do change the CFBundleName. The Apple doc Core Foundation Keys says it's "The short display name of the bundle".

Items of concern are:

  • Existing App Updates Succeeding
  • Accessing old content via NSUserDefaults.standardUserDefaults
  • Accessing old content via NSKeyedArchiver (un)archiveRootObject to/from NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) related location.

The SO post Should I avoid changing the CFBundleName of my iOS app for a new release? is what got me concerned about app updates.

We store stuff that the user has paid for into the NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,.. related location.

It's important to get this right and treat our existing users well. I appreciate any help. Thanks!


Image overlaps previous view when tapping/swiping back


I have a UIScrollView which covers one of my views entirely. I have added a background image to this same view which scrolls at a slightly different rate to the actual UIScrollView. This works absolutely fine unless I use the back swipe gesture or tap the 'Back' button. What happens is the image covers the view for about 0.5 seconds before disappearing, and it looks pretty bad.

This is what I mean:

enter image description here

As you can see, that is mid way through the gesture, and rather than being able to see the previous view, you just see the part of the image that is off to the left. It doesn't happen on the first page of the UIScrollView so I guess it's because the image is overlapping the previous view.

Here is my code:

override func viewDidLoad() {
    let pagesScrollViewSize = scrollView.frame.size
    scrollView.contentSize = CGSize(width: pagesScrollViewSize.width * CGFloat(images.count), height: pagesScrollViewSize.height)

    backgroundImageView.frame = CGRect(x: 0, y: 0, width: 2484, height: 736)
    backgroundImageView.image = UIImage(named: "SF.png")

    var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView
    visualEffectView.frame = backgroundImageView.bounds

    backgroundImageView.addSubview(visualEffectView)

    view.addSubview(backgroundImageView)
    view.sendSubviewToBack(backgroundImageView)

    scrollView.backgroundColor = UIColor.clearColor()
}

func scrollViewDidScroll(scrollView: UIScrollView) {
    loadVisiblePages()

    var factor = scrollView.contentOffset.x / (scrollView.contentSize.width - 414);
    if factor < 0 {
        factor = 0
    }
    if factor > 1 {
        factor = 1
    }

    var frame: CGRect = backgroundImageView.frame
    frame.origin.x = factor * (414 - backgroundImageView.frame.size.width)
    backgroundImageView.frame = frame
}

Anyone have any suggestions?


How to occupy the app bottom with an image?


In Xcode 6 app I have placed 2 buttons at the top and 1 image (in Aspect Fill mode) at the bottom (here fullscreen):

screenshot 1

All 3 elements are center-aligned.

For the buttons I have added 20 px constraints to the sides and top and they seem to be placed well now.

However I can not figure out, which constraints to use - to nail the image at the bottom and make it occupy the most space there.

I have tried the following:

  • Center-aligned the image
  • 20 px constraints to left, bottom and right
  • More or equal to 20 px constraing to the above button

I don't understand the warnings displayed by the Interface Builder, please tell me what is missing there (here fullscreen):

screenshot


Do I need to call CGContextSaveGState and CGContextRestoreGState?


Double checking if I need to call CGContextSaveGState and CGContextRestoreGState even when creating a new imageContext.

From what I've read in the Quartz Programming Guide, I shouldn't need to in the example below, because the I'm creating a brand new image context.

I've searched github for UIGraphicsBeginImageContextWithOptions and some folks save and restore the context and other folks do not.

// Uses a circularMask on an image
class func circularImage(image: UIImage, diameter: Int) -> UIImage {
    assert(diameter > 0, "Diameter > 0 Failed \(__FUNCTION__)")

    let frame = CGRect(x: 0.0, y: 0.0, width: Double(diameter), height: Double(diameter))
    var newImage: UIImage?

    UIGraphicsBeginImageContextWithOptions(frame.size, false, UIScreen.mainScreen().scale)

    var context: CGContextRef = UIGraphicsGetCurrentContext()
    CGContextSaveGState(context)

    let imagePath: UIBezierPath = UIBezierPath(ovalInRect: frame)
    imagePath.addClip()

    image.drawInRect(frame)

    newImage = UIGraphicsGetImageFromCurrentImageContext()

    CGContextRestoreGState(context);

    UIGraphicsEndImageContext()

    return newImage!
}


button placed on top of UIVisualEffectView not responding


I'm trying to add a button to UIVisualEffectView. However, the button that I add is not responding to touch events and I don't understand why. This is the code.

override func viewDidLoad() {
        super.viewDidLoad()
        let image = UIImage(named: "face2")
        let imageView = UIImageView(image: image)
        imageView.frame = CGRectMake(0, 0, 200, 200)
        let button = UIButton(frame: CGRectMake(50, 50, 100, 100))
        button.setTitle("huhuhu", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blackColor(), forState: .Normal)
        button.userInteractionEnabled = true

        let effect = UIBlurEffect(style: .Light)
        let blurView = UIVisualEffectView(effect: effect)
        blurView.frame = view.bounds

        view.addSubview(imageView)
        view.addSubview(blurView)
        view.addSubview(button)
    }


meaning of R, S, Da in kCGBlendMode values


I'm having trouble grasping the meaning of R = 0, R = S, R = S*Da, defined in kCGBlendMode values such as kCGBlendModeClear, kCGBlendModeCopy, kCGBlendModeSourceIn. So, to what do these symbols refer?


iOS swift custom UICollectionView with Custom Cell does not call didSelectItem


I got some issues with the following code: I created a custom Cell with a Custom UICollectionView class. I used Xib files instead of the storyboard. It never calls the didSelectItemAtIndexPath method but why? I am really desperate :'(.

    import UIKit

class CustomCollectionView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    var refreshControl : UIRefreshControl = UIRefreshControl()

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.delegate = self
        self.dataSource = self

        var flowLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = UICollectionViewScrollDirection.Vertical
        self.collectionViewLayout = flowLayout

        self.refreshControl.addTarget(self, action: "refreshData:", forControlEvents: UIControlEvents.ValueChanged)
        self.addSubview(refreshControl)

        self.userInteractionEnabled = true


        self.registerClass(CustomCollectionViewCell.self, forCellWithReuseIdentifier: "outfit")
        self.registerNib(UINib(nibName: layoutHelper.getCellXibName("CustomCollectionViewCell"), bundle: nil), forCellWithReuseIdentifier: "outfit")

        self.backgroundColor = UIColor.whiteColor()

    }

    //
    // MARK: UICollectionViewDataSource - Methods
    //

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        var cell : CustomCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("outfit", forIndexPath: indexPath) as! CustomCollectionViewCell
        cell.label.text = "Outfit #" + String(indexPath.row)
        let url = NSURL(string: "http://ift.tt/1DvKe1d")
        cell.imageView.sd_setImageWithURL(url, completed: nil)
        return cell
    }


func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        println("at index path %i", indexPath.row)
}


What's causing this memory leak?


The Problem

I'm currently building an iPad game using SpriteKit. The gameplay is driven by sound provided by EZAudio. After running the Instrumentation tools to profile my app, I noticed that whenever the GameViewController is shown memory allocation jumps up. When I repeatedly show the screen (5+ times) it crashes the app. My project uses ARC.

Navigation

The navigation consists of 4 ViewControllers:

  1. MenuViewController: This shows the menu
  2. CharacterSelectionViewController: It lets you a pick a character to use
  3. GameViewController: This lets you play a game with the player chosen
  4. ScoreViewController: It shows you the score you achieved in the game

1 - MenuViewController

From here you can navigate to CharacterSelectionViewController via a Show (e.g. Push) segue.

2 - CharacterSelectionViewController

You can navigate to GameViewController via a Show (e.g. Push) segue. There is also a back button that goes back to MenuViewController with the following code:

[self.navigationController popViewControllerAnimated:YES];

3 - GameViewController

  1. It first shows a 5 second countdown (using NSTimer)
  2. The game starts with the character chosen in CharacterSelectionViewController
  3. The game can be paused, allowing you to quit and go back to MenuViewController via a manual Show Detail (e.g. Replace) segue.
  4. When the game ends, a manual Show (e.g. Push) segue is called that navigates to the ScoreViewController.

It's view hierarchy consists of three sets of view - one for the countdown, one for the pause menu and one for the game. These are subsequently shown/hidden. See the view hierarchy below:

GameViewController View Hierarchy

4 - ScoreViewController

This allows you to quit or restart the game. When quit it pressed it performs a Show Detail (e.g. Replace) segue to MenuViewController. If restart is pressed it performs an unwind to CharacterSelectionViewController.

Responses

Please provide answers regarding:

  • How this kind of leak could occur
  • Any observations you have from the allocation and leaks screenshots

Allocation

Below, you can see the increasing allocations as I cycle through the apps screens to repeatedly show the GameViewController. I used Mark Generation to be able to show the increase in memory allocations.

Allocations

Leaks

Here you can see the memory leak that occurred. This is ordered by size.

Leaks


Any iOS 8 app extensions/extension types that work with iPhone's Message app?


While reading on app extensions introduced with iOS 8, I noticed that there are extension types that can work with an iPhone user's images, notes etc. But I was wondering if I can make an action or a share extension that would work with iPhone's Message app as the host app. Is there any resources about it?


Putting text in Circle as big as possible


It´s a pretty basic problem but I couldn´t find a proper solution for it. I have several circles which have text in it like you can see in the picture. The text gets loaded dynamically and has a size from one word up to five words or more. The goal is to put the text as big as possible into the circle. New lines can appear but every individual word should stay together. The example image is kind of ok but I would prefer the text to be bigger because there is still some free space between the text and the circle. The circle is 80x80. All solution I tried cropped the text strangly or the text is too small.

How I create the label:

UILabel *buttonlabel = [[UILabel alloc] initWithFrame:CGRectMake(12,7,57,64)];

    [buttonlabel setText: @"Text"];
    buttonlabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:18.0f];
    buttonlabel.textColor = [UIColor whiteColor];
    buttonlabel.textAlignment = NSTextAlignmentCenter;
    buttonlabel.lineBreakMode = NSLineBreakByWordWrapping;
    buttonlabel.numberOfLines = 3;
   [button addSubview:buttonlabel];
   [buttonlabel release];

enter image description here


CGRect intersects 4 rects. How to figure out which rect it intersects mostly?


If you need more details: I have UICollectionViewCell which is draggable. When the cell overlaps other cells during dragging I want to know which one it overlaps mostly in order to replace overlapped cell with this cell. Is there any efficient way to do this? I found nothing helpful in CGGeometry. Thank you.


segue.identifier = nil in second view


I have IOS Swift program, using Storyboards with NavigationController. There are two Views, lets call them mainView, secondView.

From the mainView I have BarButtonItem to go to secondView. When pressing that button, it triggers prepareForSegue function in the mainView with segue.identifier = "secondView"

When I have opend e.g. the secondView, I have two BarButtonItems for Cancel and Save. When pressing either of them the prepareForSegue function in that view is triggered, but now the segue.identifier = nil.

I would have expected to have the segue.identifier = "cancel" or "save" depended on the button pressed in that view.

Am I misunderstanding the segue functionality? Can anyone try to enlight me about this, as this looks like a very important and useful part of storyboards and navigation - but somehow I am not getting it right.


cocoa-touch resizing image logo based on screen size


Developing an app using cocoa-touch interface builder and swift. using any size class to fix the resolution issue in iPhone but the image logo which i am using is shrinking on different screen iPhone . how to fix this issue in swift and how to display image-logo based on my screen resolution?


How to save the data and show in tableview like category in ios


Hi i'm working one shopping app and i have response data's like All Categories for Example Main category has men, women,kids etc.and each one has sub-Category like T-shirts,shirts,footwear etc and that also have some sub category(ex.footwear)casual Shoes,formal shoes,scandals etc.. So how can i store this response and how to show the category in tableview please help me


Getting object at location on screen in Metal


I'm using Metal and I want the user to be able to tap certain objects onscreen. I'm using a tap gesture recognizer, and so I have a CGPoint, but I don't know how to find the object at that point. Is there either a way to get the onscreen coordinates for metal, or a way to transform the CGPoint into the metal coordinate space?


Is overriding of constraints() and removeConstraints() necessary when creating a custom control?


I'm creating a custom control that uses auto-layout to arrange its subviews.

Naturally, I don't want users of my custom control to inadvertently mess with these internal constraints when programmatically manipulating the control's constraints so I thought I should override constraints() to hide those internal ones the user should never need to know about and also removeConstraints() to prevent the user from removing them.

But then it occurred to me that UIKit itself probably invokes constraints() and/or removeConstraints() and expects to be able to see all of them.

So, should I or should I not, override constraints() and removeConstraints() ?


Creating a large GIF with CGImageDestinationFinalize - running out of memory


I'm trying to fix a performance issue when creating GIFs with lots of frames. For example some GIFs could contain > 1200 frames. With my current code I run out of memory. I'm trying to figure out how to solve this; could this be done in batches? My first idea was if it was possible to append images together but I do not think there is a method for that or how GIFs are created by the ImageIO framework. It would be nice if there was a plural CGImageDestinationAddImages method but there isn't, so I'm lost on how to try to solve this. I appreciate any help offered. Sorry in advance for the lengthy code, but I felt it was necessary to show the step by step creation of the GIF.

It is acceptable that I can make a video file instead of a GIF as long as the differing GIF frame delays are possible in a video and recording doesn't take as long as the GIF animation.

Note: jump to Latest Update heading below to skip the backstory.

Updates 1 - 6: Thread lock fixed by using GCD, but the memory issue still remains. 100% CPU utilization is not the concern here, as I show a UIActivityIndicatorView while the work is performed. Using the drawViewHierarchyInRect method might be more efficient/speedy than the renderInContext method, however I discovered you can't use the drawViewHierarchyInRect method on a background thread with the afterScreenUpdates property set to YES; it locks up the thread.

There must be some way of writing the GIF out in batches. I believe I've narrowed the memory problem down to: CGImageDestinationFinalize This method seems pretty inefficient for making images with lots of frames since everything has to be in memory to write out the entire image. I've confirmed this because I use little memory while grabbing the rendered containerView layer images and calling CGImageDestinationAddImage. The moment I call CGImageDestinationFinalize the memory meter spikes up instantly; sometimes up to 2GB based on the amount of frames. The amount of memory required just seems crazy to make a ~20-1000KB GIF.

Update 2: There is a method I found that might promise some hope. It is:

CGImageDestinationCopyImageSource(CGImageDestinationRef idst, 
CGImageSourceRef isrc, CFDictionaryRef options,CFErrorRef* err) 

My new idea is that for every 10 or some other arbitrary # of frames, I will write those to a destination, and then in the next loop, the prior completed destination with 10 frames will now be my new source. However there is a problem; reading the docs it states this:

Losslessly copies the contents of the image source, 'isrc', to the * destination, 'idst'. 
The image data will not be modified. No other images should be added to the image destination. 
* CGImageDestinationFinalize() should not be called afterward -
* the result is saved to the destination when this function returns.

This makes me think my idea won't work, but alas I tried. Continue to Update 3.

Update 3: I've been trying the CGImageDestinationCopyImageSource method with my updated code below, however I'm always getting back an image with only one frame; this is because of the documentation stated in Update 2 above most likely. There is yet one more method to perhaps try: CGImageSourceCreateIncremental But I doubt that is what I need.

It seems like I need some way of writing/appending the GIF frames to disk incrementally so I can purge each new chunk out of memory. Perhaps a CGImageDestinationCreateWithDataConsumer with the appropriate callbacks to save the data incrementally would be ideal?

Update 4: I started to try the CGImageDestinationCreateWithDataConsumer method to see if I could manage writing the bytes out as they come in using an NSFileHandle, but again the problem is that calling CGImageDestinationFinalize sends all of the bytes in one shot which is the same as before - I run out memory. I really need help to get this solved and will offer a large bounty.

Update 5: I've posted a large bounty. I would like to see some brilliant solutions without a 3rd party library or framework to append the raw NSData GIF bytes to each other and write it out incrementally to disk with an NSFileHandle - essentially creating the GIF manually. Or, if you think there is a solution to be found using ImageIO like what I've tried that would be amazing too. Swizzling, subclassing etc.

Update 6: I have been researching how GIFs are made at the lowest level, and I wrote a small test which is along the lines of what I'm going for with the bounty's help. I need to grab the rendered UIImage, get the bytes from it, compress it using LZW and append the bytes along with some other work like determining the global color table. Source of info: http://ift.tt/1JoQ77k .

Latest Update:

I've spent all week researching this from every angle to see what goes on exactly to build decent quality GIFs based on limitations (such as 256 colors max). I believe and assume what ImageIO is doing is creating a single bitmap context under the hood with all image frames merged as one, and is performing color quantization on this bitmap to generate a single global color table to be used in the GIF. Using a hex editor on some successful GIFs made from ImageIO confirms they have a global color table and never have a local one unless you set it for each frame yourself. Color quantization is performed on this huge bitmap to build a color palette (again assuming, but strongly believe).

I have this weird and crazy idea: The frame images from my app can only differ by one color per frame and even better yet, I know what small sets of colors my app uses. The first/background frame is a frame that contains colors that I cannot control (user supplied content such as photos) so what I'm thinking is I will snapshot this view, and then snapshot another view with that has the known colors my app deals with and make this a single bitmap context that I can pass into the normal ImaegIO GIF making routines. What's the advantage? Well, this gets it down from ~1200 frames to one by merging two images into a single image. ImageIO will then do its thing on the much smaller bitmap and write out a single GIF with one frame.

Now what can I do to build the actual 1200 frame GIF? I'm thinking I can take that single frame GIF and extract the color table bytes nicely, because they fall between two GIF protocol blocks. I will still need to build the GIF manually, but now I shouldn't have to compute the color palette. I will be stealing the palette ImageIO thought was best and using that for my byte buffer. I still need an LZW compressor implementation with the bounty's help, but that should be alot easier than color quantization which can be painfully slow. LZW can be slow too so I'm not sure if it's even worth it; no idea how LZW will perform sequentially with ~1200 frames.

What are your thoughts?

@property (nonatomic, strong) NSFileHandle *outputHandle;    

- (void)makeGIF
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),^
    {
        NSString *filePath = @"/Users/Test/Desktop/Test.gif";

        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];

        self.outputHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];

        NSMutableData *openingData = [[NSMutableData alloc]init];

        // GIF89a header

        const uint8_t gif89aHeader [] = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 };

        [openingData appendBytes:gif89aHeader length:sizeof(gif89aHeader)];


        const uint8_t screenDescriptor [] = { 0x0A, 0x00, 0x0A, 0x00, 0x91, 0x00, 0x00 };

        [openingData appendBytes:screenDescriptor length:sizeof(screenDescriptor)];


        // Global color table

        const uint8_t globalColorTable [] = { 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00 };

        [openingData appendBytes:globalColorTable length:sizeof(globalColorTable)];


        // 'Netscape 2.0' - Loop forever

        const uint8_t applicationExtension [] = { 0x21, 0xFF, 0x0B, 0x4E, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45, 0x32, 0x2E, 0x30, 0x03, 0x01, 0x00, 0x00, 0x00 };

        [openingData appendBytes:applicationExtension length:sizeof(applicationExtension)];

        [self.outputHandle writeData:openingData];

        for (NSUInteger i = 0; i < 1200; i++)
        {
            const uint8_t graphicsControl [] = { 0x21, 0xF9, 0x04, 0x04, 0x32, 0x00, 0x00, 0x00 };

            NSMutableData *imageData = [[NSMutableData alloc]init];

            [imageData appendBytes:graphicsControl length:sizeof(graphicsControl)];


            const uint8_t imageDescriptor [] = { 0x2C, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x0A, 0x00, 0x00 };

            [imageData appendBytes:imageDescriptor length:sizeof(imageDescriptor)];


            const uint8_t image [] = { 0x02, 0x16, 0x8C, 0x2D, 0x99, 0x87, 0x2A, 0x1C, 0xDC, 0x33, 0xA0, 0x02, 0x75, 0xEC, 0x95, 0xFA, 0xA8, 0xDE, 0x60, 0x8C, 0x04, 0x91, 0x4C, 0x01, 0x00 };

            [imageData appendBytes:image length:sizeof(image)];


            [self.outputHandle writeData:imageData];
        }


        NSMutableData *closingData = [[NSMutableData alloc]init];

        const uint8_t appSignature [] = { 0x21, 0xFE, 0x02, 0x48, 0x69, 0x00 };

        [closingData appendBytes:appSignature length:sizeof(appSignature)];


        const uint8_t trailer [] = { 0x3B };

        [closingData appendBytes:trailer length:sizeof(trailer)];


        [self.outputHandle writeData:closingData];

        [self.outputHandle closeFile];

        self.outputHandle = nil;

        dispatch_async(dispatch_get_main_queue(),^
        {
           // Get back to main thread and do something with the GIF
        });
    });
}

- (UIImage *)getImage
{
    // Read question's 'Update 1' to see why I'm not using the
    // drawViewHierarchyInRect method
    UIGraphicsBeginImageContextWithOptions(self.containerView.bounds.size, NO, 1.0);
    [self.containerView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *snapShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // Shaves exported gif size considerably
    NSData *data = UIImageJPEGRepresentation(snapShot, 1.0);

    return [UIImage imageWithData:data];
}


xcode problems installing, apple keeps telling me to upgrade?


Ive just spent the best part of 3 hours updating my mac (because apple told me xcode 6 wont run unless I install 10.7.4). However, now Ive done that, apple now tells me xcode 6 wont run unless I install 10.10? Is that right? A whole new OS with no path to upgrade?

Im wondering can I use older versions of xcode? Where can I download these? Will I still be able to submit to the app store with older versions of xcode?


How to create rounded images with WatchKit?


I'm trying to do a rounded images to be shown in my WatchKit application but I don't find any method to do it programatically.

What I have done to perform that, it is use my original image as a group background and put inside a mask image with rounded shape but I think this is not so clean.

Another different solution that I have thought is to create in my backend a new thumbnail or similar with the shape I want to show, but this require more time to be programed.

I could use also radius parameter from WKInterfaceGroup but, in my case (see the image below), I will lose my notification bubble that I have in a corner.

My app interface:

enter image description here

Uber application example:

enter image description here


iAd ADBannerView appears tinted on Device


I'm getting a tinted adBannerView on the device,instead the normal adBannerView as it appears in the Simulator. Any ideas on this?enter image description here


How do I enter text in an alert textfield using Xcode UI Automation testing


This problem is really bugging me. Having read the official documentation, the book by Jonathan Penn and all the online tutorials I can find. I have built a really simple app to learn about UI Testing but am getting stumped at the first step. Its a todo list app. I click on the UIBarButtonItem button which displays a dialog with a UITextField and two button, OK and Cancel. Here is the IBAction.

@IBAction func showDialog(sender: UIBarButtonItem) {
    println("showDialog")
    var inputTextField: UITextField?
    var alert:UIAlertController
    alert = UIAlertController(title: "New Item", message: "Type item below", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
        textField.placeholder = "Item name"  // need to choose correct keyboard and capitalise first letter of each word.
        inputTextField = textField
    })
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        if let itemName = inputTextField?.text {
            println(itemName)
            self.items.append(itemName)
            self.tableView.reloadData()
        }
    }))
    alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
}

I have tried to write a UI Automation test by recording then adding the alert handler but it won't work. Here is my testing script.

var target = UIATarget.localTarget();

UIALogger.logWarning('script started');

target.frontMostApp().navigationBar().rightButton().tap();

UIATarget.onAlert = function onAlert(alert) {
    var title = alert.name();
    UIALogger.logWarning("Alert with title ’" + title + "’ encountered!");
    target.frontMostApp().keyboard().typeString("Cheese");
    alert.buttons()["OK"].tap();
    return true;
}

What am I doing wrong?


IOS/Xcode: Name button created in storyboard name so it can be disabled


I have a button created in storyboard for taking a photo that is wired to an action. The button says "Take Photo".

If no camera is present, I would like to disable this button with something like following:

[btnOutlet setEnabled:FALSE];

How do I give the button a name or otherwise identify it so that I can disable it. IOS newb here so if you could provide code i.e. where I put this info I would appreciate it. Thank you.

Here is code I am working with currently.

   if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
  //would like to change this alert to just disable the take photo button created in storyboard          
            UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                  message:@"Device has no camera"
                                                                 delegate:nil
                                                        cancelButtonTitle:@"OK"
                                                        otherButtonTitles: nil];

            [myAlertView show];

        }
    }


iOS 8 programatic autolayout example code?


I'm looking for sample code which demonstrates how to programmatically perform autolayout (primarily in UIViewController's -viewWillLayoutSubviews method) where multiple devices and orientations are handled.

Thanks!


iTunes Connect iAd rejectet


When I submitted an update for my app, I got the following message:


During our review, we found the following:

PLA 3.3.12

We found that your app uses the iOS Advertising Identifier but does not include ad functionality. This does not comply with the terms of the iOS Developer Program License Agreement, as required by the App Store Review Guidelines.

Specifically, section 3.3.12 of the iOS Developer Program License Agreement states:

"You and Your Applications (and any third party with whom you have contracted to serve advertising) may use the Advertising Identifier, and any information obtained through the use of the Advertising Identifier, only for the purpose of serving advertising. If a user resets the Advertising Identifier, then You agree not to combine, correlate, link or otherwise associate, either directly or indirectly, the prior Advertising Identifier and any derived information with the reset Advertising Identifier."

Note: iAd does not use the AdSupport framework, ASIdentifierManager, or the Advertising Identifier. Therefore they are not required for iAd implementations and should not be included in your app for iAd support.

If your app is serving ads, please:

  • Ensure that you have tested your app on a device, not just the simulator, and that you have removed all previous versions of your app prior to testing

  • Provide us the steps to locate ads in your app

If your app does not serve ads, please check your code - including any third-party libraries - to remove any instances of:

class: ASIdentifierManager selector: advertisingIdentifier framework: AdSupport.framework

If you are planning to incorporate ads in a future version, please remove the Advertising Identifier from your app until you have included ad functionality.

To help locate the Advertising Identifier, use the “nm” tool. For information on the “nm” tool, please see the nm man page.


Can anyone please help me solve this issue? Thanks!


Terminating App - NSInvalidArgumentException


Crashing when running Parse Anypic code.

-(void)sendCommentButton:(id) sender {
        NSString *trimmedComment = [commentTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if (trimmedComment.length != 0 && [self.photo objectForKey:kPAPPhotoUserKey]) {
            PFObject *comment = [PFObject objectWithClassName:kPAPActivityClassKey];
            [comment setObject:trimmedComment forKey:kPAPActivityContentKey]; // Set comment text
            [comment setObject:[self.photo objectForKey:kPAPPhotoUserKey] forKey:kPAPActivityToUserKey]; // Set toUser
            [comment setObject:[PFUser currentUser] forKey:kPAPActivityFromUserKey]; // Set fromUser
            [comment setObject:kPAPActivityTypeComment forKey:kPAPActivityTypeKey];
            [comment setObject:self.photo forKey:kPAPActivityPhotoKey];
            [comment setObject:self.photoFile forKey:@"attachmentFile"];


            PFACL *ACL = [PFACL ACLWithUser:[PFUser currentUser]];
            [ACL setPublicReadAccess:YES];
            [ACL setWriteAccess:YES forUser:[self.photo objectForKey:kPAPPhotoUserKey]];
            comment.ACL = ACL;

            [[PAPCache sharedCache] incrementCommentCountForPhoto:self.photo];

            // Show HUD view
            [MBProgressHUD showHUDAddedTo:self.view.superview animated:YES];

            // If more than 5 seconds pass since we post a comment, stop waiting for the server to respond
            NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(handleCommentTimeout:) userInfo:@{@"comment": comment} repeats:NO];

            [comment saveEventually:^(BOOL succeeded, NSError *error) {
                [timer invalidate];

                if (error && error.code == kPFErrorObjectNotFound) {
                    [[PAPCache sharedCache] decrementCommentCountForPhoto:self.photo];
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Could not post comment", nil) message:NSLocalizedString(@"This photo is no longer available", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
                    [alert show];
                    [self.navigationController popViewControllerAnimated:YES];
                }

                [[NSNotificationCenter defaultCenter] postNotificationName:PAPPhotoDetailsViewControllerUserCommentedOnPhotoNotification object:self.photo userInfo:@{@"comments": @(self.objects.count + 1)}];

                [MBProgressHUD hideHUDForView:self.view.superview animated:YES];
                [self loadObjects];
            }];

        }

        [self.commentTextView setText:@""];
        [self.commentTextView resignFirstResponder];
        if (self.photoFile != nil) {
            self.photoFile = nil;
        }


}

Picking an Image

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSLog(@"Hello");
    UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];


    // JPEG to decrease file size and enable faster uploads & downloads
    NSData *imageData = UIImageJPEGRepresentation(img, 0.8f);

    self.photoFile = [PFFile fileWithData:imageData];

    // Request a background execution task to allow us to finish uploading the photo even if the app is backgrounded
    self.fileUploadBackgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:self.fileUploadBackgroundTaskId];
    }];

    NSLog(@"Requested background expiration task with id %lu for Anypic photo upload", (unsigned long)self.fileUploadBackgroundTaskId);
    [self.photoFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            NSLog(@"Photo uploaded successfully");
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Photo Uploaded"
                                                            message:@"successfully"
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
        } else {

            [[UIApplication sharedApplication] endBackgroundTask:self.fileUploadBackgroundTaskId];

        }
    }];

    [self dismissViewControllerAnimated:YES completion:nil];
}

enter image description here

Question: Why is it crashing? I believe this is the code that is crashing it. What I did to crash it was not add an attachmentFile and just put a comment.

If you need more code or need any clarifications please comment down below


"Flatten" frame+anchorPoint+matrix to matrix only


I have a composition made up of several CALayers and UIViews that are positioned using the frame/bounds/position properties. Some of these elements are also transformed with a CGAffineTransform — sometimes with their anchorPoint modified.

Assuming I have the proper pixel data and dimensions for these elements, I need to figure out a way to replicate the original composition using only a single transform per element.

My questions are:

  1. Is this even possible?
  2. Is there a name for doing something like this and how can I get started?

How to resize view height based on it's subview avalability dynamically with Autolayout?


I have a situation where Window has 2 subviews A and B and A view contains 2 more subviews A1 and A2. I have to show View A's height based on if A1 and A2 available or not. Example: if A1 available then A2 not then expected A's height is A1 height + padding. and View B's height re-adjust based on vertical spacing constraints between View A and B. - if A1 and A2 both available then A'height = A1 height + padding+ A2 height + padding. and the same B's height re-adjust based on vertical spacing constraints.

___________________________
| _________________________
| | A _____________________ 
| |  |_A1__________________
| |  ______________________
| | |__A2__________________
| |________________________
|
|  ________________________
| |  B
| | 
| |________________________
|
|
|__________________________


___________________________
| _________________________
| | A _____________________ 
| |  |_A1__________________
| |________________________
|
|  ________________________
| |  B
| | 
| |________________________
|
|
|__________________________


UIView bottom view like classic iOS


I have a problem with my project, I am at a point where i don't know how to. My problem is with "scrolling" or gesture with UIView. I need to create a bottom view like classic iOS bottom function bar with animation. But my view stops at for example 100px from bottom. Any tutorial or help with this?

Image here:

enter image description here


Broken navigation in UIImagePickerController


There seems to be problem with hiding status bar in UIImagePicker/UIPopoverController , below code is used to hide status bar but in UIImagePickerController navigation breaks when swiped back(In the image below you can see back button is gone).Any solution for this?

-(BOOL)prefersStatusBarHidden
{
    return YES;
}

-(void)viewWillAppear:(BOOL)animated
{
    [[UIApplication sharedApplication] setStatusBarHidden:YES];

}

- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}

-(void)navigationController:(UINavigationController *)navigationController
     willShowViewController:(UIViewController *)viewController
                   animated:(BOOL)animated
{
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}

enter image description here


iOS Animate Mask Over UIImage


I am using Swift 1.2 and my goal is to animate an image mask over a static UIImage. What I have implemented is a swift version of masking an image that I originally found in Objective-C.

func maskImage(image: UIImage, mask: UIImage) -> UIImage! {

    let maskRef = mask.CGImage;

    let mask = CGImageMaskCreate(
        CGImageGetWidth(maskRef),
        CGImageGetHeight(maskRef),
        CGImageGetBitsPerComponent(maskRef),
        CGImageGetBitsPerPixel(maskRef),
        CGImageGetBytesPerRow(maskRef),
        CGImageGetDataProvider(maskRef), nil, false);

    let masked = CGImageCreateWithMask(image.CGImage, mask);
    let retImage = UIImage(CGImage: masked);
    return retImage;
}

It works great! However, putting it in motion is my challenge.

Is there a way to either iteratively apply the mask with a different horizontal offset or a better way to approach this problem entirely - perhaps with a CALayer implementation?

Thanks for your help!

EDIT: Based on what was posted as an answer, I added this:

    let image = UIImage(named: "clouds");

    let imageView = UIImageView(image: image);
    let layer = CALayer();
    layer.contents = UIImage(named: "alpha-mask")?.CGImage;
    layer.bounds = CGRectMake(0, 0, image.size.width, image.size.height);

    let animation = CABasicAnimation(keyPath: "bounds.origin.x");
    animation.duration = 2;
    animation.delegate = self;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = 0;
    animation.fromValue = 0.0;
    animation.toValue = image.size.width;
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear);
    animation.removedOnCompletion = false;

    layer.addAnimation(animation, forKey: "transform");

    imageView.layer.mask = layer;

    self.addSubview(imageView);

I am able to see the alpha mask properly, but the animation does not work. Any ideas?


UITableViewCell edit cell content on click


I have a question about UITAbleViewCell's.

I have implemented UITableViewDelegate method

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];

    cell.textLabel.text = @"TEST!";
}

Sadly, after I click on cell, nothing happens...

Where is the problem?


Use ssl server with mqttkit in ios [on hold]


I am using MQTTKit for chat in my iPhone application.Can anyone help me in making connection of MQTTKit with ssl server.

Thanks in advance.