React-Native openURL Twitter 链接问题



我在我的应用程序中显示了一个推特提要,它是从推特API拉入的。由于推文不显示全文,因此有一个推特短代码URL(t.co(来查看完整的推文。

我遇到的问题是,当我使用 openURL 单击该 URL 时,它会在浏览器中打开,该浏览器会重定向到 Twitter 应用程序并重定向回浏览器以显示推文。

如果我已经打开了 Twitter 应用程序,这就可以了 - 如果它没有打开,最终重定向回浏览器不会加载页面。

如果没有安装Twitter应用程序,一切正常,它只是在浏览器中加载。

有没有办法避免重定向,如果安装了 twitter 应用程序,只需在 Twitter 应用程序中打开 t.co URL?

所以我设法通过首先在 PHP 中创建一个 URL 缩短器来解决这个问题:

<?php 
$url = $_GET['url'];
$context = stream_context_create(
array(
'http' => array(
'follow_location' => false
)
)
);
$html = file_get_contents($url, false, $context);
$final = str_replace("location: ",'',$http_response_header[5]);
echo json_encode ($final,JSON_PRETTY_PRINT);
?>

然后从 react-native 从取消缩短器中获取完整的 URL:

if (href.contains('https')) {
var short = {
getInfo() {
var myUrl = 'expander.php?url='+href
return fetch(myUrl).then((res) => res.json()).catch(function(error) {
Alert.alert(error+''); 
});
}
}
short.getInfo().then((res) => {
var final = res.replace('i/web','web');
Linking.openURL(final);   
})
} else {
Linking.openURL(href)
}

将URL 字符串中的"i/web"替换为"web"非常重要,这样应用才能在本地打开链接,而不是打开移动链接。

最新更新