Unable to upload image into Firebase Storage - swift 5 - ios

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

Related

Parse JSON Result To UILabel in Swift

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
}

How can I use a URL for an image in Swift?

I am trying to retrieve certain data from my Firebase Database - the profile image. As you can see, this is from a UITableViewCell. I have an #IBOutlet for my imageView I want to cover.
As the view awakens, you can see that I go through, and make sure that I can get the information. I know how to retrieve data from Firebase, but not photo URLs, and then convert to the photo itself.
I'm not sure why it isn't working. I am getting an error, and will show it below. There is a possibility it is because of the URL unwrapping stuff, or as if the Firebase isn't formatted correctly, which I think it is, though.
Error Message : Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
import UIKit
import FirebaseAuth
import FirebaseDatabase
import Firebase
class ProfileCellControler: UITableViewCell {
#IBOutlet var name : UILabel!
#IBOutlet var rating : UILabel!
#IBOutlet var imageViewPro : UIImageView!
var databaseRefer : DatabaseReference!
var databaseHandle : DatabaseHandle!
override func awakeFromNib() {
super.awakeFromNib()
var urlString = ""
let urll = URL(string: urlString)!
databaseRefer = Database.database().reference()
let userID = Auth.auth().currentUser!.uid
databaseHandle = databaseRefer.child("Users").child(userID).child("Profile").child("Profile Name").observe(.value, with: { (data) in
print(String((data.value as? String)!))
self.name.text = "\(String((data.value as? String)!))"
print("Done")
})
databaseHandle = databaseRefer.child("Users").child(userID).child("Profile").child("Stars").observe(.value, with: { (data) in
print(String((data.value as? String)!))
if ((String((data.value as? String)!)) == "N/A") {
self.rating.text = "No Rating"
} else {
self.rating.text = "\(String((data.value as? String)!)) ★"
}
print("Done")
})
databaseHandle = databaseRefer.child("Users").child(userID).child("Profile").child("Profile Image").observe(.value, with: { (data) in
print(String((data.value as? String)!))
print("Done \(String((data.value as? String)!))")
urlString = (String((data.value as? String)!))
})
ImageService.downloadImage(withURL: urll) { (image) in
self.imageViewPro.image = image
}
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
The string for the URL is found nil because you are creating the call to download the image for your url before the urll has been initialized with a value from the database in:
databaseHandle = databaseRefer.child("Users").child(userID).child("Profile").child("Profile Image").observe(.value, with: { (data) in
print(String((data.value as? String)!))
print("Done \(String((data.value as? String)!))")
urlString = (String((data.value as? String)!))
})
observe(.value, with: ) Is an asynchronous operation thus
ImageService.downloadImage(withURL: urll) { (image) in
self.imageViewPro.image = image
}
Is being called before observe(.value, with:) is resolved. I would recommend moving the callback for the download URL inside of the completion for .observe(:value, :with) or using grand central dispatch to control the flow better.
As a side note, I highly recommend SDWebImage for handling your image downloading needs as it is configurable with a default image for situations such as this when the image fails to load.
Import KingFisher to make your life easier and then..
Download string representation of image from Firebase asynchronically.
Assign downloaded image to imageView with .kf.setImage method.

Cant connect to web socket of Hasura PostGreSQL docker container

We need a realtime database which we can deploy using docker.
I found a Hasura/PostGreSQL docker container which looks like we can use it for our purpose:
https://docs.hasura.io/1.0/graphql/manual/getting-started/docker-simple.html
One thing I figured out was that the URL in the documentation was wrong. It's http://localhost:8080/v1/graphql and not http://localhost:8080/graphql.
But I can't seem to get any results from my subscription...
I get a BAD_ACCESS crash in the package's SplitNetworkTransport.swift
Am I missing something?
My Apollo client code looks like this:
import Apollo
import ApolloWebSocket
class Apollo {
static let shared = Apollo()
let client: ApolloClient = {
let authPayloads = [ "x-hasura-admin-secret": "secret" ]
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = authPayloads
let wsEndpointURL = URL(string: "ws://localhost:8080/v1alpha1/graphql")!
let endpointURL = URL(string: "http://localhost:8080/v1alpha1/graphql")!
let map: GraphQLMap = authPayloads
let websocket = WebSocketTransport(request: URLRequest(url: wsEndpointURL), connectingPayload: map)
let httpNetworkTransport = HTTPNetworkTransport( url: endpointURL, session: URLSession(configuration: configuration))
let splitTransport = SplitNetworkTransport(httpNetworkTransport: httpNetworkTransport, webSocketNetworkTransport: websocket)
return ApolloClient(networkTransport: splitTransport)
}()
}
And I'm calling it as follows:
import UIKit
import Apollo
class ViewController: UIViewController {
private var subscription: Cancellable?
#IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.subscription = Apollo.shared.client.subscribe(subscription: MySubscriptionSubscription()) { [weak self] result in
guard let this = self else { return }
switch result {
case .success(let graphQLResult):
if let data = graphQLResult.data {
this.label.text = "data"
print("Simon Says data: \(data)")//TODO: Remove
}
case .failure(let error):
this.label.text = "error"
print("Simon Says error: \(error)")//TODO: Remove
}
}
}
deinit {
self.subscription?.cancel()
}
}
P.s. I'm using Xcode Version 11.2.1 (11B500), swift 5.1, Apollo swift package 0.20.0 and the docker-compose.yaml from the URL in the Hasura docs linked above.
The workaround is NOT using swift package manager and use COCOAPODS instead.

NSLocalizedDescription=Object StringOfNumbers/post1/StringOfNumbers.StringOfNumbers.jpg does not exist

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!

iOS Swift & Parse - getDataInBackground not working?

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)
}
}
})

Resources