将图片上传到Firebase

我正尝试将图片上传到Firebase,如下所示:

Firebase *ref = [[Firebase alloc] initWithUrl:@"https://<app-name>.firebaseio.com/posts"]; Firebase *newPost = [ref childByAutoId]; NSDictionary *newPostData = @{ @"image" : [self encodeToBase64String:image] }; [newPost updateChildValues:newPostData]; 

我正在使用此代码来编码图像:

 - (NSString *)encodeToBase64String:(UIImage *)image { return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; } 

但是,这不符合string的最大尺寸:

Terminating app due to uncaught exception 'InvalidFirebaseData', reason: '(updateChildValues:) String exceeds max size of 10485760 utf8 bytes:

我能做些什么来解决这个问题? 在使用Firebase时,我没有在网上find关于iOS开发和图片的任何信息。

如果图像太大,则应该存储较小的图像。 让我引用自己: 如何通过android将文件保存到Firebase主机文件夹位置以获取图像?

Firebase数据库允许您存储JSON数据。 尽pipe二进制数据不是JSON支持的types,但是可以使用base64编码二进制数据,从而将图像存储在(大)string中。 [但]虽然这是可能的,但不build议任何东西,但小图像或作为好奇心,看看它可以完成。

您的最佳select通常是将图像存储在第三方图像存储服务上。

正如Frank van Puffelen所说,我的解决scheme是使用Amazon S3进行想象存储,并使用Firebase存储对映像位置的引用。

我创build了一个名为uploadImage:的方法uploadImage:它看起来像这样:

 -(void)uploadImage:(UIImage *)image { // Create reference to Firebase Firebase *ref = [[Firebase alloc] initWithUrl:@"https://<MY-APP>.firebaseio.com"]; Firebase *photosRef = [ref childByAppendingPath:@“photos]; Firebase *newPhotoRef = [photosRef childByAutoId]; // Image information NSString imageId = [[NSUUID UUID] UUIDString]; // Create dictionary containing information NSDictionary photoInformation = @{ @“photo_id” : imageId // Here you can add more information about the photo }; NSString *imagePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageId]]; NSData *imageData = UIImagePNGRepresentation(image); [imageData writeToFile:imagePath atomically:YES]; NSURL *imageUrl = [[NSURL alloc] initFileURLWithPath:imagePath]; AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new]; uploadRequest.bucket = @“<AMAZON S3 STORAGE NAME>“; // create your own by setting up an account on Amazon aws. uploadRequest.key = imageId; uploadRequest.contentType = @"image/png"; uploadRequest.body = imageUrl; AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager]; [[transferManager upload:uploadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor] withBlock:^id(AWSTask *task) { if (!task.error) { // Update Firebase with reference [newPhotoRef updateChildValues:currentPHD withCompletionBlock:^(NSError *error, Firebase *ref) { if (!error) { [newPhotoRef updateChildValues:photoInformation withCompletionBlock:^(NSError *error, Firebase *ref) { if (!error) { // Uploaded image to Amazon S3 and reference to Firebase } }]; } }]; } else { // Error uploading } return nil; }]; } 

编辑该方法应该是一个块方法,如下所示:

 -(void)uploadImage:(UIImage *)image withBlock:(void (^)(Firebase *ref, NSError *error, AWSTask *task))handler { // upload }