When I press a button which takes me to another view controller which is supposed to download a url of an image in firebase so that it can be displayed in a imageView. I receive the following message in the console:
Error Domain=FIRStorageErrorDomain Code=-13010 "Object 8MFEIQKyGuTnMI89kMG2E8D9IZ2/post1/153511633.59902.jpg does not exist." UserInfo={object=8MFEIQKyGuTnMI89kGF2E8D9IZ2/post1/1535511633.59902.jpg, ResponseBody=NoSuchKeyThe specified key does not exist.No such object: prjpracticearraybasicimg.appspot.com/8MFEIQKyGuTnMI89kMGF2E8D9IZ2/post1/1535511633.59902.jpg, bucket=yubipracticearraybasicimg1.appspot.com, data=<3c3f786d 6c207665 7273696f 6e3d2731 2e302720 656e636f 64696e67 3d275554 462d3827 3f3e3c45 72726f72 3e3c436f 64653e4e 6f537563 684b6579 3c2f436f 64653e3c 4d657373 6167653e 5466520 73706563 69666965 6420665 7920646f 6573206e 6f742065 78697374 2e3c2f4d 65737361 67653ec 44657461 696c733e 4e6f2073 75636820 6f626a65 63743a20 7975269 70726163 74696365 61727261 79626173 6963696d 67312e61 70707370 6f742e63 6f6d2f38 4d464549 514b7947 75546e4d 4938396b 4d474632 45384439 495a322f 706f7374 312f3135 33353531 31363333 2e353939 30322e6a 70673c2f 44657461 696c733e 3c2f4572 726f723e>, data_content_type=application/xml; charset=UTF-8, NSLocalizedDescription=Object 8MFEIQKyGuTnMI89kMGF28D9IZ2/post1/155511633.59902.jpg does not exist., ResponseErrorDomain=com.google.HTTPStatus, ResponseErrorCode=404}
The following is my code:
import UIKit
import FirebaseStorage
import FirebaseDatabase
import FirebaseAuth
import Firebase
class PhaseOneViewController: UIViewController {
#IBOutlet weak var p1ImageView: UIImageView!
#IBAction func loadImages(_ sender: Any) {
self.downloadImages(folderPath: "\(Storage.storage().reference().child((Auth.auth().currentUser?.uid)!).child("post\(takePicViewController().finalPost + PhotoArray.sharedInstance.numberPost)").child(ImageUploadManager().imageName))", success: { (img) in
self.p1ImageView.image = img
print(img)
}) { (error) in
print("here is errorrrrrrrrrrr", error)
}
}
func downloadImages(folderPath:String,success:#escaping (_ image:UIImage)->(),failure:#escaping (_ error:Error)->()){
// for i in 0 ..< 194 {
// Create a reference with an initial file path and name
let reference = Storage.storage().reference().child((Auth.auth().currentUser?.uid)!).child("post\(takePicViewController().finalPost + PhotoArray.sharedInstance.numberPost)").child(ImageUploadManager().imageName)
reference.getData(maxSize: (3 * 1024 * 1024)) { (data, error) in
if let _error = error {
print(_error)
failure(_error)
} else {
if let _data = data {
let myImage:UIImage! = UIImage(data: _data)
success(myImage)
self.p1ImageView.image = myImage
}
}
}
//}
}
}
The Database tree structure is as follows
Posts/UID/post#/ImageURLs-URL1, URL2...
Thanks for any help!
Related
I'm really new into swift & currently learning API by doing a project that shows list of games from rawg.io referring to the website's doc. I created GameFeed.swift & GameDetail.swift to pull name, release date, and rating from it and working fine in my console.
GameFeed.swift :
struct GameFeed: Codable {
let results:[GameDetail]
}
GameDetail.swift :
struct GameDetail: Codable {
let name:String
let released:String
let rating:Double
}
Now i'm trying to put the results to a simple UIlabel like gameName.text, gameReleased.text & gameRating.text from ViewController.swift so it will be show in Main.Storyboard
i did research on google about how to show it to these UIlabel by using DispatchQueue.main.async but when i'm declaring it, it receiving error :
Value of type 'GameFeed' has no member 'name'
same error messages also happened to released & rating. This is my ViewController.Swift :
class ViewController: UIViewController {
#IBOutlet weak var gameName: UILabel!
#IBOutlet weak var gameReleased: UILabel!
#IBOutlet weak var gameRating: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Defining API Site
let urlString = "https://api.rawg.io/api/games"
let url = URL(string: urlString)
guard url != nil else {
return
}
// Calling API
let session = URLSession.shared
let dataTask = session.dataTask(with: url!){
(data, response, error) in
if error == nil && data != nil {
let decoder = JSONDecoder()
do {
let gameFeed = try decoder.decode(GameFeed.self, from: data!)
print(gameFeed)
DispatchQueue.main.async {
self.gameName.text = gameFeed.name
self.gameReleased.text = gameFeed.released
self.gameRating.text = gameFeed.rating
}
}
catch {
print("Error Parsing JSON")
}
}
}
dataTask.resume()
}
}
What should i do to make it possible to parse the data to labels?
The GameFeed contains an Array of GameDetails. But you are trying to set a single GameDetail on those labels. You should first pull out a single GameDetail from that array, then assign it in a way you like.
DispatchQueue.main.async {
let gameDetail = gameFeed.results.first // <- This will return the first one
self.gameName.text = gameDetail?.name
self.gameReleased.text = gameDetail?.released
self.gameRating.text = gameDetail?.rating
}
I can't upload an image into Firebase Storage
I found this error in my output log
"An SSL error has occurred and a secure connection to the server
cannot be made."
and last output is
print("check: 4 >> Don't put image")
Then the least of the code doesn't execute therefore the image still not uploading
In the putData method i also use url parameter but also got the same problem
MY Full code is
import UIKit
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage
class ViewController: UIViewController {
#IBOutlet weak var imageview: UIImageView!
#IBOutlet weak var emailTextView: UITextField!
#IBOutlet weak var passwordTextView: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func buttonAction(_ sender: Any) {
Auth.auth().createUser(withEmail: emailTextView.text!, password: passwordTextView.text!){ (result, error) in
if let _eror = error {
print(_eror.localizedDescription)
return
}
print("check: 1 >> After creating user\(result!)")
let uid = result?.user.uid
let storage = Storage.storage()
let storageRef = storage.reference(forURL: "gs://porate-chai-4deee.appspot.com").child("profile_image").child(uid!)
print("check: 2 >> \(storageRef)")
if let profileImage = self.imageview!.image, let imageData = profileImage.jpegData(compressionQuality: 0.1) {
print("check: 3 >> \(imageData)")
storageRef.putData(imageData, metadata: nil) { (metadata, error) in
if error != nil {
print("check: 4 >> Don't put image")
return
}
print("put image on firebase storage")
storageRef.downloadURL(completion: {(url, error) in
if error != nil {
print(error!.localizedDescription)
return
}
let downloadURL = url?.absoluteString
print(downloadURL!)
let ref = Database.database().reference()
print("seeref\(ref)")
let userReference = ref.child("tutor")
let newUserReference = userReference.child(uid!)
newUserReference.setValue([
"email": self.emailTextView.text!,
"profileimageurl": downloadURL!
])
})
}
}
}
}
}
My Firebase Storage Rules is
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
I also try this rules
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
}
With the help of this answer
"flutter pub get" can't get dependency plugins on Windows
After 27-03-2020 the code still work but after 28-03-2020 have some problem storage.googleapis.com in Bangladesh.
To overcome this issue, use VPN tool and re-run your project.
I used Hotspot Sheild VPN and after that everything was good.
I use this
Hotspot Shield: Fastest
VPNwww.hotspotshield.com
Then the file again uplod
I have a GMSPlace object and I want to get the image URL for that place but the Google Places SDK doesn't seem to allow for that.
loadImageForMetadata only returns an object of type UIImage. I don't need the image just the URL.
How do I find the image url for a given Google Place ID? Here's a class I've written to help me work with the Google Places SDK:
import Foundation
import GooglePlaces
class GoogleImageService: NSObject {
class func loadFirstPhotoForPlace(placeID: String) {
GMSPlacesClient.shared().lookUpPhotos(forPlaceID: placeID) { (photos, error) -> Void in
if let error = error {
print("Error: \(error.localizedDescription)")
}
if let firstPhoto = photos?.results[0] {
self.loadImageForMetadata(photoMetadata: firstPhoto, placeID: placeID)
}
}
}
class func loadImageForMetadata(photoMetadata: GMSPlacePhotoMetadata, placeID: String) {
GMSPlacesClient.shared().loadPlacePhoto(photoMetadata, callback: { (photo, error) -> Void in
if let error = error {
print("Error: \(error.localizedDescription)")
}
// photo parameter in the closure is an UIImage, not helpful
})
}
}
Currently learning Swift & iOS. I try to access with Parse a saved picture. However, I can't access it with getDataInBackground(block:).
Here's my code:
//
// ViewController.swift
// Instragram
//
// Created by Macbook Pro on 22.07.17.
// Copyright © 2017 Macbook Pro. All rights reserved.
//
import UIKit
import Parse
class ViewController: UIViewController {
#IBOutlet weak var picture: UIImageView!
#IBOutlet weak var senderLbl: UILabel!
#IBOutlet weak var recieverLbl: UILabel!
#IBOutlet weak var messageLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Creating tables and data in database
let imageData = UIImageJPEGRepresentation(picture.image!, 0.5)
let file = PFFile(name: "picture.jpg", data: imageData!)
let table = PFObject(className: "messages")
table["sender"] = "Akhmed"
table["reciver"] = "Bob"
table["picture"] = file
table["message"] = "Hello!"
table.saveInBackground {(success, error) -> Void in
if(success){
print("Saved successful")
} else {
print(error!)
}
}
//Recieving Data from the Server
let information = PFQuery(className: "messages")
information.findObjectsInBackground{(objects: [PFObject]?, error) -> Void in
if error == nil {
for object in objects!{
self.senderLbl.text = object["sender"] as? String
self.recieverLbl.text = object["reciver"] as? String
self.messageLbl.text = object["message"] as? String
object["picture"].getDataInBackground(...)
}
} else {
print(error!)
}
}
}
}
Down after I access the name, receiver and message string I try to access an image that has been saved on there server with:
object["picture"].getDataInBackground(block:)
However, Swift won't even autocorrect anymore after I've typed object["picture"]. I get also an error:
'Value of type "Any" has no Member 'getDataInBackground(block:)'
Any ideas what's wrong? It seems to me that Swift can't find the string picture even though the image is saved on the server under the string "picture".
You need to first cast it as a PFFfile object and then retrieve the actual image data with getDataInBackground function like this:
let imageFile = object["picture"] as? PFFile
imageFile?.getDataInBackground (block: { (data, error) -> Void in
if error == nil {
if let imageData = data {
self.myImage = UIImage(data:imageData)
}
}
})
I am trying to play with the Image Alignment Analysis part of the new Vision API but i am struggling with the initialisation of VNTranslationalImageRegistrationRequest. My code is as follows:
import UIKit
import Vision
class ImageTranslation {
var sourceImage: UIImage!
lazy var imageTranslationRequest: VNTranslationalImageRegistrationRequest = {
//This line fails let translationRequest = VNTranslationalImageRegistrationRequest(targetedCGImage: sourceImage.cgImage, completionHandler: self.handleImageTranslationRequest)
return translationRequest
}()
func handleImageTranslationRequest(request: VNRequest, error: Error?) {
guard let observations = request.results as? [VNImageTranslationAlignmentObservation]
else { print("unexpected result type from VNDetectRectanglesRequest")
return
}
guard observations.first != nil else {
return
}
DispatchQueue.main.async {
observations.forEach { observation in
let transform = observation.alignmentTransform
print(transform)
}
}
}
}
But on the marked line above i keep getting the following error and am unsure how to fix it. Instance member 'sourceImage' cannot be used on type 'ImageTranslation'
Can anyone point me in the right direction? Thanks
An example how to use VNTranslationalImageRegistrationRequest on two images to compute the translation between the two images:
import UIKit
import Vision
class ImageTranslation {
func translateImages(for referenceImage: UIImage,
floatingImage: UIImage,
completion: #escaping (_ alignmentTransform : CGAffineTransform?) -> Void) {
let translationRequest = VNTranslationalImageRegistrationRequest(targetedCGImage: floatingImage.cgImage!) { (request: VNRequest, error: Error?) in
completion((request.results?.first as? VNImageTranslationAlignmentObservation)?.alignmentTransform)
}
let vnImage = VNSequenceRequestHandler()
try? vnImage.perform([translationRequest], on: referenceImage.cgImage!)
}
}