0

this is my JSON Structure

Users:

simpleLogin1:

  • Name
  • email
  • password
  • Image

this is how i created ref and user :

   var ref = Firebase(url: "https://chatty93.firebaseio.com/")
   var userId = authData.uid

                        let newUser = [
                            "Provider" : authData.provider,
                            "email"    : authData.providerData["email"] as? NSString as? String,
                            "name"     : self.Name.text,
                            "Image"    : "",
                        ]
                   self.ref.childByAppendingPath("users").childByAppendingPath(authData.uid).setValue(newUser)

the name email and password provided by the logged in user on first view controller then on another view controller the user provides the image. for this i have an image view for the image on this view controller , the user will select it and press the update button to update the image of his profile, now how do i save this image in my firebase and then retrieve it to display it also on any other view controller ..

thiagowfx
  • 4,832
  • 6
  • 37
  • 51
Shahzaib Qureshi
  • 989
  • 8
  • 13
  • so you looking to upload your images to a JSON page – Lamour Sep 06 '15 at 17:38
  • i found a way of encoding the image data into a NSstring and saving it on firebase , i have tried it i think the image have been saved but now how do i retrieve it? – Shahzaib Qureshi Sep 07 '15 at 09:40
  • Possible duplicate of [Swift2 retrieving images from Firebase](http://stackoverflow.com/questions/33644560/swift2-retrieving-images-from-firebase) – thiagowfx Apr 29 '16 at 22:25

1 Answers1

1

I know the answer. But Before I start to explain it. Our tools are Alamofire 3.0, Firebase 2.5, Imageshackapi and Imageshack.

Our application can do posting images and posting text.

//
//  Post.swift
//  firebase social network
//
//  Created by durul dalkanat on 1/21/16.
//  Copyright © 2016 durul dalkanat. All rights reserved.

import Foundation

class Post {
    private var _postDescription: String!
    private var _imageUrl: String?
    private var _postKey: String!

    var postDescription: String {
        return _postDescription
    }

    var imageUrl: String? {
        return _imageUrl
    }



    init(description: String, imageUrl: String?) {
        self._postDescription = description
        self._imageUrl = imageUrl
    }

    init(postKey: String, dictionary: Dictionary<String, AnyObject>) {
        self._postKey = postKey

        if let imgUrl = dictionary["imageUrl"] as? String {
            self._imageUrl = imgUrl
        }

        if let desc = dictionary["description"] as? String {
            self._postDescription = desc
        }
    }
}

And Let's coding viewcontroller. But You should configure customtableviewCell yourself.

//
//  ViewController.swift
//  firebase social network
//
//  Created by durul dalkanat on 1/21/16.
//  Copyright © 2016 durul dalkanat. All rights reserved.
//

import UIKit
import Firebase
import Alamofire

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var postField: UITextField!

    @IBOutlet weak var postImg: UIImageView!

    var posts = [Post]()
    var imageSelected = false
    var imagePicker: UIImagePickerController!

    static var imageCache = NSCache()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        tableView.estimatedRowHeight = 358
        imagePicker = UIImagePickerController()
        imagePicker.delegate = self

        //Sync data with Firebase
        DataService.ds.REF_POSTS.observeEventType(.Value, withBlock: { snapshot in
            print(snapshot.value)

            //Parsing firebase data
            self.posts = []
            if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {

                for snap in snapshots {

                    if let postDict = snap.value as? Dictionary<String, AnyObject> {
                        let key = snap.key
                        let post = Post(postKey: key, dictionary: postDict)
                        self.posts.append(post)
                    }

                }

            }

            self.tableView.reloadData()
        })

    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let post = posts[indexPath.row]

        if let cell = tableView.dequeueReusableCellWithIdentifier("PostCell") as? PostCell {

            cell.request?.cancel()

            var img: UIImage?

            if let url = post.imageUrl {
                img = ViewController.imageCache.objectForKey(url) as? UIImage
            }

            cell.configureCell(post, img: img)

            return cell
        } else {
            return PostCell()
        }
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

        let post = posts[indexPath.row]

        if post.imageUrl == nil {
            return 150
        } else {
            return tableView.estimatedRowHeight
        }
    }


    @IBAction func selectImage(sender: UITapGestureRecognizer) {
        presentViewController(imagePicker, animated: true, completion: nil)
    }

    @IBAction func makePost(sender: AnyObject) {

        if let txt = postField.text where txt != "" {

            if let img = postImg.image {
                let urlStr = "https://post.imageshack.us/upload_api.php"
                let url = NSURL(string: urlStr)!

                //compression quality.
                let imgData = UIImageJPEGRepresentation(img, 0.2)!

                //Converting data from strings
                let keyData = "You should write own api number here".dataUsingEncoding(NSUTF8StringEncoding)!

                //Converting data from json
                let keyJSON = "json".dataUsingEncoding(NSUTF8StringEncoding)!


                Alamofire.upload(.POST, url, multipartFormData: { multipartFormData in

                    //Check this documentaion https://code.google.com/p/imageshackapi/wiki/ImageshackAPI
                    multipartFormData.appendBodyPart(data: imgData, name:"fileupload", fileName:"image", mimeType: "image/jpg")
                    multipartFormData.appendBodyPart(data: keyData, name: "key")
                    multipartFormData.appendBodyPart(data: keyJSON, name: "format")

                    }) { encodingResult in

                        switch encodingResult {

                        case .Success(let upload, _, _):
                            upload.responseJSON(completionHandler: { response in

                                let result = response.result
                                print(result.value?.debugDescription)

                                if let info = result.value as? Dictionary<String, AnyObject> {

                                    if let links = info["links"] as? Dictionary<String, AnyObject> {
                                        print(links)
                                        if let imgLink = links["image_link"] as? String {
                                            self.postToFirebase(imgLink)
                                        }
                                    }
                                }
                            })

                        case .Failure(let error):
                            print(error)
                            //Maybe show alert to user and let them try again
                        }
                }
            } else {
                postToFirebase(nil)
            }


        }

    }

    //Saving Posts to Firebase
    func postToFirebase(imgUrl: String?) {

        var post: Dictionary<String, AnyObject> = [
            "description":postField.text!     
   ]

        if imgUrl != nil {
            post["imageUrl"] = imgUrl!
        }

        //Save new post to firebase
        let fbPost = DataService.ds.REF_POSTS.childByAutoId()
        fbPost.setValue(post)

        //Clear out fields
        self.postField.text = ""
        self.postImg.image = UIImage(named: "camera")

        tableView.reloadData()
    }

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        imagePicker.dismissViewControllerAnimated(true, completion: nil)
        postImg.image = image
        imageSelected = true

    }
}

I hope, this code block will help you. But Don't forget test data couldn't update immediately.

This is my scheme.

enter image description here

Durul Dalkanat
  • 7,266
  • 4
  • 35
  • 36