South Africa beat New Zealand 31-29 at the death in a classic, intense encounter in the Rugby Championship.