The Washington Post did a piece on this saying, quoting author Caroline Taggart, saying it was first used in the 1860s as a longer rhyming couplet that has become more succinct over time. A phrase from the 1860s is recent to Taggart, though “The fruit also pops up in traditional Ayurvedic medicine, dating back about 1,500 years in southern Asia,” though the word “apple” could mean any round fruit grown on a tree.
Skeptics SE mentions an Italian version of the saying. The UK’s Phrase Finder specifies the source as the1866 edition of Notes and Queries magazine which quoted this as a Pembrokeshire proverb, so the phrase was already in use.