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.
