The Iberian Union, consisting of the united kingdoms of Spain and Portugal, fell apart in 1640. When a Portuguese king died with an heir as the Spanish king, the crown passed to the Spanish, finally uniting the Iberian Peninsula under one crown. When the ruler of the union, under King Philip II of Spain and Philip I* of Portugal, died, and then Philip II and III died, and later when his heir, Philip III and IV, who had different ideas about how to rule the union, the kingdom broke apart and Portugal regained its independence, while Aragon remained a part of Spain. A day later, King John IV was recognized as the king by all Portugal.
*This is the same person. Since the rulers of the union held more than one title, they could be recognized as Philip I of Portugal or Philip II of Spain