Ice first. When an injury occurs the bodies reaction is to protect the injured site by filling it with fluid (swelling). The swelling was designed to stop you from using the injured area until it had healed. Of course this was before the time of rehabilitation to speed recovery.
Ice is a vasoconstrictor which will cause the vessels around the injured area to contract limiting the amount of swelling that will enter the area, and allowing swelling that is there to dissipate.
Heat is a vasodilator, making the vessels bigger. That will allow more swelling to enter the area causing the discomfort and pain to actually increase.
Once the swelling cycle is broken heat can be safely applied and the opening of the vessels will allow the swelling to exit.
There is not set time on when its ok to apply heat. A good rule of thumb is to use ice until the swelling subsides significantly. Sometimes 3 days for some injuries it can be over a week.
Ice time needs to be limited as well. Any more than 20-30 minutes at a time is too much. The body will perceive the prolonged icing to be dangerous and will dump more fluid into the area to protect it from damage. Between icings the body needs enough time to re-warm itself. This usually takes about an hour.