Needing a goal, Iran changed strategy and it almost paid off when Saeid Ezatolahi thought he had leveled but his goal was ruled out after the use of VAR.
Spain was lucky not to concede toward the end as Mehdi Taremi connected with a cross from Ansarifard, but his header from close range went over the crossbar.
Spain are level with Portugal on four points in Group B and face Morocco in their final group fixture on Monday.
His gesture went unpunished, and the Atletico Madrid striker required another stroke of luck on 54 minutes when his shot came off Ramin Rezaeian to beat Beiranvand after he had been sent through by Andres Iniesta.
Costa was accused of standing on the foot of Iran's Ali Beiranvand.
"But this was our first match point, if we compare this to tennis, our second match point comes against Portugal".More news: One Killed, Four Injured in Sweden Shooting
More news: Salman Khan is the 'worst Bollywood actor', according to Google
More news: Disney, Epilepsy Foundation issues seizure warning for ‘Incredibles 2’ movie
The Iranians entered the match as underdogs, but had a World Cup win under their belts following their opening game win over the Moroccans. Cautious optimism will be the order of the day, and Iran boss Carlos Queros side will be looking for a similarly defensively strong performance against one of the favourites for the World Cup. Iran 0-1 Spain It's hard to know what happened there, perhaps offside, perhaps handball, perhaps a foul.
Carlos Queiroz's charges were doing well in stifling Spain of spaces in their defensive third, although they were living dangerously.
On a rare counter goalkeeper David De Gea was left irate when Taremi rose to head a metre wide.
When does the FIFA World Cup 2018 Match-20 between Iran vs Spain start?
While only one of them was a clear-cut opportunity Silva dropped deeper after the break and looked to gather the ball further away from goal.
David Silva also showed moments of class in the game against Portugal, seemingly never losing possession and keeping Spain's passing game going in midfield.
It went unpunished by Uruguayan referee Cunha, who had awarded France a historic first VAR-assisted penalty that saw Antoine Griezmann score Les Bleus' opener in a 2-1 win over Australia.