Created
December 27, 2018 09:51
-
-
Save GaborWnuk/b430c6af35d921850c600f79f6e86b7d to your computer and use it in GitHub Desktop.
App.js for React Native CarPlay
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component, PureComponent } from "react"; | |
import { FlatList, Image, NativeModules, StyleSheet, Text, TouchableOpacity, View } from "react-native"; | |
import { ReactNativeAudioStreaming } from "react-native-audio-stream"; | |
type ChannelLogo = { url: string }; | |
type Channel = { id: number, name: string, logo: ChannelLogo }; | |
type ChannelItemType = { logo: ChannelLogo, name: string }; | |
const ChannelItem = ({ channel }: Channel) => ( | |
<TouchableOpacity | |
style={styles.channelItemContainer} | |
onPress={() => { | |
const url = `https://stream.open.fm/${channel.id}`; | |
ReactNativeAudioStreaming.stop(); | |
ReactNativeAudioStreaming.play(url, { showIniOSMediaCenter: true, showInAndroidNotifications: true }); | |
}} | |
> | |
<Image style={styles.channelItemLogo} source={{ uri: `https://open.fm/logo/96x96/${channel.id}` }} /> | |
<Text>{channel.name}</Text> | |
</TouchableOpacity> | |
); | |
type Props = {}; | |
type State = { channels: Array<Channel>, current: Channel }; | |
export default class App extends Component<Props, State> { | |
state = { channels: [] }; | |
getChannels = async () => { | |
const response = await fetch("https://open.fm/radio/api/v2/ofm/stations_slug.json"); | |
return await response.json(); | |
}; | |
componentDidMount() { | |
this.getChannels().then(channels => { | |
this.setState({ channels: channels.channels }); | |
const { RNChannels } = NativeModules; | |
RNChannels.setChannels(channels.channels); | |
}); | |
} | |
render() { | |
const { channels } = this.state; | |
return ( | |
<FlatList | |
contentContainerStyle={styles.content} | |
style={styles.container} | |
keyExtractor={(channel, index) => channel.id} | |
data={channels} | |
renderItem={({ item }) => <ChannelItem channel={item} />} | |
/> | |
); | |
} | |
} | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
backgroundColor: "#F5FCFF", | |
paddingTop: 24 | |
}, | |
channelItemContainer: { flexDirection: "row", alignItems: "center", padding: 8 }, | |
channelItemLogo: { width: 32, height: 32, marginRight: 8 } | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment