将图像存储到登录用户

时间:2015-09-06 17:18:48

标签: ios swift firebase

这是我的JSON结构

用户:

simpleLogin1:

  • 姓名
  • 电子邮件
  • 密码
  • 图像

这就是我创建ref和用户的方式:

   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)

登录用户在第一个视图控制器上提供的名称电子邮件和密码,然后是用户提供图像的另一个视图控制器。 为此我在这个视图控制器上有一个图像的图像视图,用户将选择它并按更新按钮来更新他的配置文件的图像,现在我如何在我的firebase中保存此图像然后检索它以显示它也可以在任何其他视图控制器上..

1 个答案:

答案 0 :(得分:1)

我知道答案。但在我开始解释之前。我们的工具是Alamofire 3.0,Firebase 2.5,Imageshackapi和Imageshack。

我们的应用程序可以发布图片和发布文本。

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

让我们编码viewcontroller。但是您应该自己配置customtableviewCell。

//
//  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

    }
}

我希望,这个代码块可以帮到你。但不要忘记测试数据无法立即更新。

这是我的计划。

enter image description here