Pagination
Difficulty: Medium
In this exercise, you will build an image search app using the free Unsplash API. The app should allow users to search for images, display results in a grid layout, implement lazy-loading pagination, and present a detailed photo view when an image is tapped.
Requirements
Welcome Screen
- When the app is opened, display a welcome screen before any search occurs.
- (Bonus) Consider using a random Unsplash image as a background.
Search
- A search bar at the top of the screen.
- The app should only trigger a search when the user enters at least 3 characters. Debounce input to limit excessive API calls when the user is typing.
- Display fetched images in a two-column grid layout.
- (Bonus) Implement a Masonry Layout, which arranges images dynamically based on height, similar to Pinterest.
ℹ️
A Masonry Layout is a grid-like structure that arranges photos into columns while preserving their original aspect ratios, ensuring each image fills the available width without distortion. Instead of enforcing uniform row heights, each new image is placed in the column with the least total height, allowing the layout to distribute images naturally and minimize empty spaces.
Pagination
Fetch search results using Unsplash’s pagination API.
- Track the current page and increment only when a new page is needed. Check
total_pagesbefore making additional requests to avoid redundant API calls. - Trigger new fetches when the user scrolls near the end of the list.
Photo Detail Screen
When a user taps on an image, open a detail screen that includes:
- The full-size image.
- The author’s name, with a link to their Unsplash profile.
- The number of likes.
- The photo description, if available.
API Documentation
Getting Started
Create an Unsplash account and register an application via Unsplash Developers. Obtain an API Key (Access Key) to authenticate API requests.
Search
GET https://api.unsplash.com/search/photos
| Parameter | Required | Description |
|---|---|---|
query |
✅ | The search term. |
page |
❌ | Page number (default: 1). |
per_page |
❌ | Number of results per page (default: 10, max: 30). |
Sample Request & Response
GET https://api.unsplash.com/search/photos?query=beach&page=2&per_page=15&client_id=YOUR_ACCESS_KEY
{
"total": 500,
"total_pages": 50,
"results": [
{
"id": "abc123",
"urls": {
"raw": "https://images.unsplash.com/photo-abc123",
"full": "https://images.unsplash.com/photo-abc123?fm=jpg&w=1080",
"regular": "https://images.unsplash.com/photo-abc123?fm=jpg&w=800",
"small": "https://images.unsplash.com/photo-abc123?fm=jpg&w=400"
},
"user": {
"name": "John Doe",
"links": {
"html": "https://unsplash.com/@johndoe"
}
},
"likes": 250,
"description": "A beautiful beach at sunset."
}
]
}
Pagination
- Request: Specify
pageandper_pagevalues to retrieve results. - Response: The API response includes
total_pages– check this to prevent unnecessary requests.