-
Notifications
You must be signed in to change notification settings - Fork 20
/
ImageBrowser.js
124 lines (114 loc) · 2.83 KB
/
ImageBrowser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import React from 'react'
import {
View,
Text,
Button,
Image,
ActivityIndicator,
StyleSheet,
Dimensions,
ScrollView,
CameraRoll,
TouchableHighlight,
Platform,
Alert
} from 'react-native'
import RNFetchBlob from 'react-native-fetch-blob'
const { width, height } = Dimensions.get('window')
let styles
class ImageBrowser extends React.Component {
static navigationOptions = {
title: 'Unsplash Images',
}
state = {
images: [],
loading: true,
page: 1
}
componentDidMount() {
this.fetchPhotos()
}
fetchPhotos = () => {
this.setState({ loading: true })
fetch(`https://api.unsplash.com/photos/?page=${this.state.page}&per_page=30&client_id=${YOURAPPID}`)
.then(res => res.json())
.then(images => {
this.state.images.push(...images)
console.log('this.state.images: ', this.state.images)
this.setState({ images: this.state.images, loading: false, page: this.state.page + 1 })
})
}
saveToCameraRoll = (image) => {
if (Platform.OS === 'android') {
RNFetchBlob
.config({
fileCache : true,
appendExt : 'jpg'
})
.fetch('GET', image.urls.small)
.then((res) => {
CameraRoll.saveToCameraRoll(res.path())
.then(Alert.alert('Success', 'Photo added to camera roll!'))
.catch(err => console.log('err:', err))
})
} else {
CameraRoll.saveToCameraRoll(image.urls.small)
.then(Alert.alert('Success', 'Photo added to camera roll!'))
}
}
render() {
return (
<View style={{flex: 1}}>
<Text style={styles.title}>Unsplash Images</Text>
{
this.state.loading ? (
<Text style={{ padding: 10, textAlign: 'center' }}>Loading...</Text>
) : (
<Button
onPress={this.fetchPhotos}
title='View More'
/>
)
}
<ScrollView contentContainerStyle={styles.scrollContainer}>
{
this.state.images.map((image, i) => {
return (
<TouchableHighlight
key={i}
onPress={() => this.saveToCameraRoll(image)}
underlayColor='transparent'
>
<Image
style={styles.image}
source={{ uri: image.urls.small }}
/>
</TouchableHighlight>
)
})
}
</ScrollView>
</View>
)
}
}
styles = StyleSheet.create({
scrollContainer: {
flexDirection: 'row',
flexWrap: 'wrap'
},
centerLoader: {
height: height - 100,
width,
justifyContent: 'center',
alignItems: 'center'
},
image: {
width: width / 2, height: width / 2
},
title: {
textAlign: 'center',
padding: 20
}
})
export default ImageBrowser