facebook ios sdk upload photo to album
ane. Introduction
What y'all volition build
In this codelab, you'll build a field trip app, Field Trippa, that enables users to share photos.
Larn how to use the Google Photos Library API to back a media sharing experience in your own awarding.
The app for this codelab was congenital using Palpitate, Google's UI toolkit for building cute, natively compiled applications for mobile, web, and desktop from a single codebase. Larn more at https://palpitate.dev.
What you'll learn
- How to employ the Google Photos Library API to upload media and share albums
- How to use Google Sign-In in Flutter
- How to make Google API calls from Flutter
What you'll need
- Flutter development environs
- Two Google user accounts set up on dissimilar emulators or devices that have access to Google Photos, so you can examination sharing between users
- An Android device, emulator or physical iOS device - the iOS simulator is not supported due to missing camera hardware
Overview over the Field Trip Gallery App - "Field Trippa"
In this codelab you will build an app to share photos for an excursion or field trip, built using the Google Photos Library API.
The user logs in using Google Sign-In and authorizes the application to apply the Google Photos Library API.
Then, the user can create a trip
for uploading photos with a description. Each trip
tin be shared with other members of the application, who can also contribute photos.
Under the hood, each trip
is stored as a shared album inside Google Photos. The app handles sharing and uploading to this album, but you tin also share the album with others who do not have the app directly through a URL to Google Photos.
What would you like to learn from this codelab?
2. Download the Lawmaking
Download the source lawmaking for this codelab:
To clone the GitHub repository from the command line, apply the following command:
git clone https://github.com/flutter/codelabs flutter-codelabs
The sample lawmaking is cloned into a flutter-codelabs
directory that contains the code for a collection of codelabs. The lawmaking for this codelab is in flutter-codelabs/photos-sharing
. You can besides browse the code on GitHub.
The directory structure under flutter-codelabs/photos-sharing
contains the initial and the final steps. The starter lawmaking is in initial
, so locating the matching files is as like shooting fish in a barrel every bit:
cd palpitate-codelabs/photos-sharing/initial
If yous want to skip forward, or see what something should look like after a pace, wait in the final
directory that contains the finished code for this codelab.
Open the initial code:
Open the directory flutter-codelabs/photos-sharing/initial
in your preferred Palpitate IDE, for example VSCode or Android Studio with the Dart and Flutter plugins installed.
3. Run the App
Follow these steps to get your development environment set up, if you haven't developed with Flutter earlier.
To run the "Field Trippa" app click the "run" button in your development IDE, or apply the following control from the root directory of the source code:
flutter run
You should run into the "Connect with Google Photos" screen:
4. Set up the Google Photos Library API
The Google Photos Library API requires you lot to authenticate your users using OAuth two.0. Users sign into the application and qualify it to interact with the API on their behalf.
You can discover some additional troubleshooting tips at the cease of this step.
Create a new Firebase project and register your app
Get to the Firebase console and select "+ Add together Project". Enter a project proper name and select "Create Project" to proceed. Practice not follow any other steps in the Firebase console. Instead, render to this codelab and go on to the "Android" or "iOS" parts beneath to configure the application.
Android only: If you are running the app on Android, register an Android app:
Click the Android icon to open the Android app registration screen.
For package, enter:
com.google.codelab.photos.sharing
Think the signing certificate SHA-1 from your machine:
On Windows run the following command:
keytool -alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore -listing -five -storepass android
On Mac or Linux, run the following command:
keytool -alias androiddebugkey -keystore ~/.android/debug.keystore -list -five -storepass android
Click "register app" to continue.
Download the
google-service.json
file to your computer and move it into the directory "android/app/
". (Tip: In Android Studio, you tin can drag the downloaded file straight into the correct location in the project side panel.)
This file contains the project configuration for the Firebase and Google Developers project y'all have only fix up.
(See the documentation for the package google_sign_in for details.)
You lot don't accept to complete whatever other steps in the Firebase console. The Firebase SDK has already been added to the application.
iOS only: If yous are running the app on iOS, register an iOS app in Firebase:
Click the iOS icon to open the iOS app registration screen.
For iOS bundle ID, enter:
com.google.codelab.photos.sharing
Click "next" to continue.
Download the
GoogleService-Info.plist
file to your computer.
Open the Flutter projection in Xcode
Right click on Runner directory, select "Add Files to Runner" and select the
GoogleService-Info.plist
file you lot have downloaded to add it to the Runner module.
Edit the source code of the file
ios/Runner/Info.plist
and add the value of the property REVERSED_CLIENT_ID
from the file GoogleService-Info.plist
. Replace the entry at the bottom of the file:
ios/Runner/Info.plist
<!-- Google Sign-in Department --> <key>CFBundleURLTypes</fundamental> <array> <dict> <key>CFBundleTypeRole</key> <string>Editor</string> <key>CFBundleURLSchemes</key> <array> <string>COPY_REVERSED_CLIENT_ID_HERE</cord> </assortment> </dict> </array> <!-- End of the Google Sign-in Section -->
(See the documentation for the bundle google_sign_in for more details.)
Enable the Google Photos Library API
Open the API screen in the Google Developers panel and enable the "Google Photos Library API". (You may take to select the Firebase project at the top of the screen first if the "enable" push is disabled.)
Open the OAuth consent screen configuration in the Google Developers panel to add the Google Photos Library API scopes and your e-mail accost. (This configuration is required for the OAuth verification review for any scopes used past the Google Photos Library API.) You do not have to submit for verification, just you need to consummate the form and save your response. This will enable the scopes for development and testing.
- Enter the "Application Name", for example
Field Trippa Codelab
- Select a "Support electronic mail address"
- Select "Add scope", then "manually add paste scopes" to enter the following scopes:
https://www.googleapis.com/auth/photoslibrary https://www.googleapis.com/auth/photoslibrary.sharing
- Select "Save"
- There is no need to submit for verification to continue with this codelab. This is only required when launching your awarding, merely not for personal testing.
Run the app and sign in
Google Sign-In has already been implemented using the google_sign_in flutter package. This package requires the google-services.json
or GoogleService-Info.plist
files that you take already copied into the project.
Run the application again and select "Connect to Google Photos". Yous'll be prompted to select a user business relationship and accept the authentication scopes.
If everything has been set up successfully, yous'll encounter an empty list on the next screen.
Troubleshooting sign in
If you are having trouble signing into the application, here are a few things y'all tin bank check:
Check that the device has Internet connectivity.
If you receive the error
PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: x: , zero)
, make sure that you lot have followed all steps in the section Enable the Google Photos Library API. You must add the Google Photos Library API scopes, enter a back up email address and select relieve.
If y'all receive the erro
r PlatformException(sign_in_failed, com.google.android.gms.mutual.api.ApiException: 12500: , null)
, make sure that you take added a support email accost in the Firebase console. Open Firebase console and navigate to the project settings by selecting the gear icon side by side to your project title. Select an email address under support email on the general settings screen.
Cheque the signing certificate SHA-1 that is configured in the Firebase console. Does information technology match the output from the keytool command from the first footstep? Does it friction match the output from the command
./gradlew signingReport
when run in the android/
project? You may need to besides include the signing document SHA-256 in the console.
Check the package proper noun and iOS parcel ID that are configured in the Firebase panel. This should exist set to
com.google.codelab.photos.sharing
Check the location of the configuration files you have downloaded from the Firebase panel. For Android, the file should be copied to
android/app/google-service.json
. For iOS information technology should be added to the Runner module.
Yous may need to enable Google every bit a sign-in provider for your Firebase project. Open the Firebase console and navigate to Authentication and Sign-in method. Ensure that Google is enabled.
5. Create an anthology
Before yous implement the first API call to the Google Photos Library API, let'southward walk through the information architecture that the "Field Trippa" app uses.
App Architecture
- Each screen is implemented every bit a dissever page:
- The
PhotosLibraryApiModel
describes the information model of the awarding and abstracts the Google Photos Library API calls away. - The HTTPS Residue calls to the Library API are implemented in the
PhotosLibraryApiClient
. Each telephone call provided by this form takes a*Request
object where yous specify parameters and options for a call. - The Library API requires user authentication via OAuth2. The access token required to be included in all API calls is set straight by the google_sign_in parcel on the
PhotosLibraryApiClient
.
Implement the create albums API call
Each trip is stored equally an anthology in Google Photos. When yous select the "CREATE A TRIP Album" button, you should prompt the user for the proper name of the trip and create a new anthology with this proper noun as its title.
In
create_trip_page.dart
, write the logic that makes a request to the Library API to create the anthology. Implement the _createTrip(...)
method at the end of the file to call the PhotosLibraryApiModel
with the name of the trip the user entered.
lib/pages/create_trip_page.dart
Future<void> _createTrip(BuildContext context) async { // Display the loading indicator. setState(() => _isLoading = truthful); await ScopedModel.of<PhotosLibraryApiModel>(context) .createAlbum(tripNameFormController.text); // Hide the loading indicator. setState(() => _isLoading = false); Navigator.pop(context); }
Implement the call to the Library API that creates the album. In the API model, implement the
createAlbum(...)
method that takes the title of the album as a parameter. It makes a call to the PhotosLibraryApiClient
where the actual Remainder call is made.
lib/model/photos_library_api_model.dart
Future<Album?> createAlbum(String title) async { final album = await client!.createAlbum(CreateAlbumRequest.fromTitle(title)); updateAlbums(); return album; }
Implement the REST call to create the album in
photos_library_api_client.dart
. Remember that the CreateAlbumRequest
already contains the title
belongings- required for this telephone call.
The following encodes it as JSON and adds the hallmark headers to authorize the request. Finally, return the album created by the API.
lib/photos_library_api/photos_library_api_client.dart
Future<Album> createAlbum(CreateAlbumRequest asking) async { terminal response = await http.post( Uri.parse('https://photoslibrary.googleapis.com/v1/albums'), body: jsonEncode(asking), headers: await _authHeaders, ); printError(response); return Album.fromJson(jsonDecode(response.body)); }
Try it out!
Deploy the app and select "+ Create Trip".
6. Only show your app'due south albums
You may take noticed that the trips listing shows other albums from Google Photos that were non created by your app. (If you lot do non have any other albums in Google Photos and want to meet this behaviour, open the Google Photos app and create an anthology. Withal, this is non required to keep in this codelab.)
Remember that each trip is stored as an album in Google Photos. However, it does not make sense to show any other albums from Google Photos that were created through other ways - Field Trippa should merely bear witness trips that the app has created.
You lot can use the API to restrict the list of trips that are displayed to evidence just those created by the app.
Alter the method
listAlbums()
method (NOT listSharedAlbums()
!) in photos_library_api_client.dart
. This method makes the REST call to retrieve a listing of albums. Add together the parameter excludeNonAppCreatedData=true
that restricts the returned data to exclude albums that were non created by this app.
lib/photos_library_api/photos_library_api_client.dart
Hereafter<ListAlbumsResponse> listAlbums() async { final response = wait http.become( Uri.parse('https://photoslibrary.googleapis.com/v1/albums?' 'pageSize=50&excludeNonAppCreatedData=true'), headers: look _authHeaders); ... }
Endeavour it out!
The start page now only shows trips that were created past the app.
7. Upload Photos
The next footstep is to upload photos to a trip. The data is stored in your user'due south Google Photos business relationship, so you don't take to worry nearly storage or processing the information yourself.
Taking a photo in Flutter
Commencement, implement the method
_getImage(...)
in the contribute photo dialog. This method is called when the user clicks the "+Add Photograph" button.
The post-obit lawmaking uses the image_picker
bundle to have a photo, update the UI and call the API model to upload the image. (You'll implement this in the next step.) The _getImage(...)
call stores an upload token needed later to create the photo in Google Photos.
lib/components/contribute_photo_dialog.sprint
Future _getImage(BuildContext context) async { // Employ the image_picker packet to prompt the user for a photo from their // device. final pickedImage = await (_imagePicker.getImage( source: ImageSource.camera, )); if (pickedImage == null) { // No epitome selected. return; } terminal pickedFile = File(pickedImage.path); // Shop the prototype that was selected. setState(() { _image = pickedFile; _isUploading = true; }); // Make a request to upload the paradigm to Google Photos once it was selected. final uploadToken = wait ScopedModel.of<PhotosLibraryApiModel>(context) .uploadMediaItem(pickedFile); setState(() { // In one case the upload process has completed, store the upload token. // This token is used together with the description to create the media // particular later on. _uploadToken = uploadToken; _isUploading = false; }); }
Implement Library API telephone call to upload the image to become an upload token
Uploading photos and videos to the Library API is washed in two steps:
- Upload the media bytes to receive an upload token
- Create a media item in the user's library from the upload token
Implement the REST request to upload media. You lot need to set some headers to specify the blazon of upload request and the filename. In the file
photos_library_api_client.dart
implement the method uploadMediaItem(...)
where the file is uploaded, returning the upload token that the HTTP phone call returns:
lib/photos_library_api/photos_library_api_client.dart
Future<String> uploadMediaItem(File image) async { // Get the filename of the image final filename = path.basename(image.path); // Fix the headers required for this request. final headers = <Cord, String>{}; headers.addAll(await _authHeaders); headers['Content-blazon'] = 'awarding/octet-stream'; headers['X-Goog-Upload-Protocol'] = 'raw'; headers['10-Goog-Upload-File-Name'] = filename; // Brand the HTTP request to upload the epitome. The file is sent in the body. last response = wait http.post( Uri.parse('https://photoslibrary.googleapis.com/v1/uploads'), body: image.readAsBytesSync(), headers: await _authHeaders, ); printError(response); return response.body; }
Next, implement the cosmos of a media particular in the user's library from the upload token.
Creating a media item requires the upload token, an optional clarification (for example, the caption of the photograph or video) and the optional identifier of an album. Field Trippa always adds the uploaded photo straight to a trip anthology.
Implement the call to the
photos_library_api_client
that calls mediaItems.batchCreate
with the upload token, description, and album ID. In the API model, implement the method createMediaItem(...)
that calls the Library API. This method returns a media particular.
(The photos_library_client
for this call is already implemented.)
lib/model/photos_library_api_model.dart
Futurity<BatchCreateMediaItemsResponse?> createMediaItem( String uploadToken, String? albumId, String? description) async { // Construct the request with the token, albumId and description. terminal request = BatchCreateMediaItemsRequest.inAlbum(uploadToken, albumId, description); // Make the API call to create the media item. The response contains a // media item. final response = wait client!.batchCreateMediaItems(asking); // Impress and return the response. impress(response.newMediaItemResults?[0].toJson()); render response; }
Try it out!
Open the app and select a trip. Click contribute and select a photograph that yous have taken previously. Enter a clarification and select upload. The image should appear in the trip afterwards a few seconds.
Open the anthology in the Google Photos app - you'll encounter the new image in the album of this trip.
eight. Share albums with non-app users
So far you have implemented the functionality to create a trip and upload photos with a clarification into it. In the backend, each trip is stored every bit an album in Google Photos.
Adjacent, you lot will share a trip with others who are not using your application.
Each trip is backed past an album in Google Photos, therefore y'all can 'share' an album via a URL and make it available to anyone who has this URL.
Albums are shared from the trip folio when a share button at the pinnacle of the album is pressed.
Implement the asynchronous call
_shareAlbum(...)
that calls to the model to share the album and and so reloads the displayed album. By reloading the album, the shareInfo
holding is propagated which contains the shareableUrl
that you'll evidence the user in a dialog later.
lib/pages/trip_page.sprint
Future<void> _shareAlbum(BuildContext context) async { String? id = anthology.id; if (id == null) { // Album is missing an ID. const snackBar = SnackBar( elapsing: Duration(seconds: 3), content: Text('Could non share album. Try reopening this folio.'), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); render; } // Prove the loading indicator setState(() => _inSharingApiCall = true); const snackBar = SnackBar( duration: Elapsing(seconds: 3), content: Text('Sharing Album...'), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); // Share the album and update the local model expect ScopedModel.of<PhotosLibraryApiModel>(context).shareAlbum(id); final updatedAlbum = look ScopedModel.of<PhotosLibraryApiModel>(context).getAlbum(id); impress('Anthology has been shared.'); setState(() { anthology = updatedAlbum; // Hide the loading indicator _inSharingApiCall = false; }); }
Implement the method
_showShareableUrl(...)
that is called when the user clicks the "SHARE WITH ANYONE" push at the top of the page. Showtime, cheque if the anthology has already been shared and call the method _showUrlDialog(...)
once it has been shared.
lib/pages/trip_page.dart
Time to come<void> _showShareableUrl(BuildContext context) async { if (album.shareInfo == zippo || album.shareInfo!.shareableUrl == null) { print('Not shared, sharing anthology starting time.'); // Album is not shared yet, share information technology beginning, then display dialog await _shareAlbum(context); _showUrlDialog(context); } else { // Album is already shared, display dialog with URL _showUrlDialog(context); } }
Implement the method
_showUrlDialog(...)
that shows the shareableUrl
in a dialog.
lib/pages/trip_page.dart
void _showUrlDialog(BuildContext context) { print('This is the shareableUrl:\due north${album.shareInfo!.shareableUrl}'); _showShareDialog( context, 'Share this URL with anyone. ' 'Anyone with this URL can access all items.', album.shareInfo!.shareableUrl!); }
Effort information technology out!
The app only lists trips that are not shared still on the main screen. Don't worry, we'll implement that in the next step. For now, yous can simply create a new trip if you navigate abroad from the screen.
Open the app and select a trip. Select "SHARE WITH ANYONE" at the top of the screen and open the returned URL in your browser. (Tip: the URL is also printed to the log, and then you can easily copy it on your computer. In Android Studio, the log is displayed in the "Run" tab.)
ix. Share albums inside your app
In Google Photos, albums tin exist shared via a URL that anyone with access to the URL tin access. Through the Library API you can also share albums via share tokens. A share token is a string that is used within your application to bring together users to a shared anthology via the API.
The process for sharing an album by your application via the Library API looks like this:
- User A logs into your application and authorizes the Library API
- Create the album
- Share the anthology using the identifier of the album
- Transfer the share token to another User
The joining process is similar:
- User B logs into your awarding and authorizes the Library API
- Retrive the share token for the anthology the user should join
- Join the album using the share token
Shared albums are shown inside Google Photos on the "sharing" tab.
In the previous step you already implemented the method _shareAlbum(...)
that shares an album. The shareInfo
property too contains the "share token" that will exist shown on screen.
On the trip folio, implement the method
_showShareToken(...)
that is called when the user presses the "SHARE WITH FIELD TRIPPA" button on screen.
lib/pages/trip_page.dart
Future<void> _showShareToken(BuildContext context) async { if (album.shareInfo == null) { print('Non shared, sharing anthology first.'); // Anthology is not shared still, share it offset, then display dialog look _shareAlbum(context); _showTokenDialog(context); } else { // Album is already shared, display dialog with token _showTokenDialog(context); } }
Next, implement the display of the "share token" in the method _showTokenDialog(...)
. The token is role of the shareInfo
property of an album.
lib/pages/trip_page.dart
void _showTokenDialog(BuildContext context) { print('This is the shareToken:\due north${album.shareInfo!.shareToken}'); _showShareDialog( context, 'Use this token to share', album.shareInfo!.shareToken!); }
The application currently simply lists albums that are endemic by the user, but not shared albums.
Only albums that the user has created or explicitly added to their Google Photos library are shown on the "Albums" screen within the Google Photos app. Only these albums are returned when calling albums.list in the Library API. However, in our app the user can join other user'due south shared albums, which are only returned in the phone call to list shared albums. You lot need to change the way the list of trips (albums) are retrieved from the Library API to include both owned and shared albums.
Albums are loaded and cached in the API Model. Change the implementation of
updateAlbums()
in the model to load albums and shared albums, before storing them every bit one list.
This implementation uses multiple Futures to list the albums asynchronously before combining them into the list of cached albums. Delete the quondam implementation and comment out the new code.
lib/model/photos_library_api_model.dart
void updateAlbums() async { // Reset the flag before loading new albums hasAlbums = false; // Clear all albums _albums.clear(); // Skip if not signed in if (!isLoggedIn()) { return; } // Add albums from the user'southward Google Photos account // var ownedAlbums = await _loadAlbums(); // if (ownedAlbums != null) { // _albums.addAll(ownedAlbums); // } // Load albums from endemic and shared albums concluding list = expect Future.wait([_loadSharedAlbums(), _loadAlbums()]); _albums.addAll(list.expand((a) => a ?? [])); notifyListeners(); hasAlbums = true; }
Yous tin join users of your application to an anthology by using the share token. This is done through a simple text dialog in this codelab.
Implement the
_joinTrip
method on the bring together trip page that calls the API model with the share token the user has entered. First, display the loading indicator, then brand the call to join the shared album with the input from the text form, before hiding the loading indicator and returning back to the previous screen.
lib/pages/join_trip_page.dart
Future<void> _joinTrip(BuildContext context) async { // Show loading indicator setState(() => _isLoading = true); // Telephone call the API to join an album with the entered share token await ScopedModel.of<PhotosLibraryApiModel>(context) .joinSharedAlbum(shareTokenFormController.text); // Hide loading indicator setState(() => _isLoading = false); // Return to the previous screen Navigator.pop(context); }
Endeavour it out!
You demand a 2nd device or emulator with a different user account to try out this part of the codelab.
Create and share a trip under one user, then select the "SHARE IN FIELD TRIPPA" option to retrieve the share token. Copy this share token to the other device or emulator and enter it via the "Join A TRIP ALBUM" option on the dwelling house page. (Tip: The clipboard between your emulators and your host computer is shared.)
Real globe implementation tips
When you implement sharing in a real earth application (and not a codelab), you should think carefully virtually how you can use share tokens to bring together users to albums. Consider storing them in your secure backend and using your relationships between users to create and join albums.
For example - a soccer society come across upwards application could proceed track of attendees to particular scheduled events and only join the attendees to the album after prompting them.
Before making any changes in your user's Google Photos business relationship, it is important to give your users notice and inquire for consent. Review the Google Photos Library API UX guidelines for more information.
10. Summary
What you have built
- Implemented sharing functionality into your application, backed by Google Photos
- Create your own photo and video sharing experiences on meridian of the Google Photos Library API, without having to worry about infrastructure or storage
- Using the sharing functionality that is role of the API in interesting and novel means to share content directly to your users.
- Used some key parts of the Library API:
- Created new albums and uploaded new photos
- Listed shared albums, express to albums created past your awarding
Where to get next
Run across the developer documentation for the Google Photos APIs at https://developers.google.com/photos to detect out more most sharing media and other parts of the Library API. For example smart content filters powered by machine learning to aid you discover the right photos and videos.
When you are getting gear up to launch your integration, join the Google Photos partner plan.
Don't forget to review the UX guidelines and technical best practices. To aid you become started, client libraries are likewise available for some languages.
gonzalezsheithers.blogspot.com
Source: https://codelabs.developers.google.com/codelabs/google-photos-sharing
Post a Comment for "facebook ios sdk upload photo to album"