我正在使用Xcode构建Instagram应用。
在我的项目中,我对图像应用了过滤器,但是当我将其发送到数据库并在另一个视图中检索它时,该过滤器没有显示。
这是在应用滤镜之后,它在主视图中显示时没有滤镜:
过滤器查看代码:
//
// FillterVC.swift
// InstaPJT1
//
// Created by MacBook Pro on 06/11/2019.
// Copyright © 2019 MacBook Pro. All rights reserved.
//
import UIKit
protocol FillterVCDelegate {
func transformPhotoToCamera (image : UIImage)
}
class FillterVC: UIViewController {
@IBOutlet weak var imagePostOUtLet: UIImageView!
@IBOutlet weak var collectionViewOUtLet: UICollectionView!
var delegate : FillterVCDelegate?
var selectedImage : UIImage!
var filters = [
"CIPhotoEffectChrome",
"CIPhotoEffectFade",
"CIPhotoEffectInstant",
"CIPhotoEffectNoir",
"CIPhotoEffectProcess",
"CIPhotoEffectTonal",
"CIPhotoEffectTransfer",
"CISepiaTone"
]
override func viewDidLoad() {
super.viewDidLoad()
self.imagePostOUtLet.image = selectedImage
// Do any additional setup after loading the view.
}
@IBAction func cancelButton(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func nextButton(_ sender: Any) {
dismiss(animated: true, completion: nil)
delegate?.transformPhotoToCamera(image: imagePostOUtLet.image!)
}
func resizeImageScale (image : UIImage , newWidth : CGFloat)-> UIImage {
let scale = newWidth / image.size.width
let newHeigh = image.size.height * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth , height: newHeigh))
image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeigh))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
extension FillterVC : UICollectionViewDelegate , UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return filters.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FillterCell", for: indexPath) as! FillterCell
let newImage = resizeImageScale(image: selectedImage, newWidth: 200)
print(selectedImage.size)
print(newImage.size)
let ciImage = CIImage(image: newImage)
let filter = CIFilter(name: filters[indexPath.item])
filter?.setValue(ciImage, forKey: kCIInputImageKey)
if let filterdImage = filter?.value(forKey: kCIOutputImageKey) as! CIImage? {
cell.filteredImageOutLet.image = UIImage(ciImage: filterdImage)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let ciImage = CIImage(image: selectedImage)
let filter = CIFilter(name: filters[indexPath.item])
filter?.setValue(ciImage, forKey: kCIInputImageKey)
if let filterdImage = filter?.value(forKey: kCIOutputImageKey) as! CIImage? {
imagePostOUtLet.image = UIImage(ciImage: filterdImage)
}
}
}
摄像机视图:
//
// CameraVC.swift
// InstaPJT1
//
// Created by MacBook Pro on 22/01/2019.
// Copyright © 2019 MacBook Pro. All rights reserved.
//
import UIKit
import SVProgressHUD
import AVFoundation
class CameraVC: UIViewController {
@IBOutlet weak var reomveButtonLabel: UIBarButtonItem!
@IBOutlet weak var photo: UIImageView!
@IBOutlet weak var captionTextVIew: UITextView!
@IBOutlet weak var shareButton: UIButton!
var selectedPhotoToDataBase : UIImage?
var selectedVidoeToDataBase : URL?
override func viewDidLoad() {
super.viewDidLoad()
let tapGuster = UITapGestureRecognizer(target: self, action: #selector(CameraVC.handelPhtotSelected))
photo.addGestureRecognizer(tapGuster)
photo.isUserInteractionEnabled = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
handelPostsEmpty()
}
@objc func handelPostsEmpty () {
// if selectedPhotoToDataBase != nil {
// shareButton.isEnabled = true
// reomveButtonLabel.isEnabled = true
// shareButton.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
// } else {
// shareButton.isEnabled = false
// reomveButtonLabel.isEnabled = false
// shareButton.backgroundColor = .lightGray
//
//
// }
}
@objc func handelPhtotSelected () {
print("user try to tap on photo")
let photoPicker = UIImagePickerController()
photoPicker.delegate = self
photoPicker.mediaTypes = ["public.image","public.movie"]
present(photoPicker, animated: true, completion: nil)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
@IBAction func share_onTouch(_ sender: Any) {
// view.endEditing(true)
print("ndndndndnd")
if let profileIMG = self.selectedPhotoToDataBase , let imageData = profileIMG.jpegData(compressionQuality: 0.1) {
let ratio = profileIMG.size.width / profileIMG.size.height
print("image size = \(ratio)")
HelperService.UploadDataToStorage(vidoeURL : selectedVidoeToDataBase , imageData: imageData, ratio : ratio , captionTextVIew: captionTextVIew.text
, OnSuccess: {
SVProgressHUD.showSuccess(withStatus: "تم النشر بنجاح")
self.Clean()
}) { (error) in
SVProgressHUD.showError(withStatus: error)
}
}
}
@objc func Clean () {
self.captionTextVIew.text = ""
self.photo.image = UIImage(named: "placeholder-photo")
self.tabBarController?.selectedIndex = 0 // بعد ما ينحفظ البوست راح ترجع بنا الصفحة الى الصفحة الرئيسية
self.selectedPhotoToDataBase = nil
}
@IBAction func removeButton(_ sender: Any) {
self.captionTextVIew.text = ""
self.photo.image = UIImage(named: "placeholder-photo")
self.selectedPhotoToDataBase = nil
SVProgressHUD.showSuccess(withStatus: "Removed")
handelPostsEmpty()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Fillter_Segue" {
let fitlervc = segue.destination as! FillterVC
fitlervc.selectedImage = selectedPhotoToDataBase
fitlervc.delegate = self
}
}
}
extension CameraVC : UIImagePickerControllerDelegate , UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// Local variable inserted by Swift 4.2 migrator.
let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)
print(info)
if let vidoeURL = info["UIImagePickerControllerMediaURL"] as? URL {
if let thumbnailForVidoe = self.thubmnailImageForFileURL(vidoeURL) {
photo.image = thumbnailForVidoe
selectedPhotoToDataBase = thumbnailForVidoe
selectedVidoeToDataBase = vidoeURL
}
dismiss(animated: true, completion: nil)
}
if let photoSelectedFromLibriry = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage {
photo.image = photoSelectedFromLibriry
selectedPhotoToDataBase = photoSelectedFromLibriry
self.dismiss(animated: true) {
self.performSegue(withIdentifier: "Fillter_Segue", sender: nil)
}
}
}
func thubmnailImageForFileURL (_ file : URL) -> UIImage? {
let asset = AVAsset(url: file)
let imageGenenartor = AVAssetImageGenerator(asset: asset)
do {
let thumbImage = try imageGenenartor.copyCGImage(at: CMTimeMake(value: 7, timescale: 4), actualTime: nil)
return UIImage(cgImage: thumbImage)
} catch let error {
print(error)
}
return UIImage()
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] {
return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)})
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String {
return input.rawValue
}
extension CameraVC : FillterVCDelegate {
func transformPhotoToCamera(image: UIImage) {
self.photo.image = image
}
}
主视图:
//
// HomeVC.swift
// InstaPJT1
//
// Created by MacBook Pro on 22/01/2019.
// Copyright © 2019 MacBook Pro. All rights reserved.
//
import UIKit
import SVProgressHUD
import SDWebImage
class HomeVC: UIViewController {
@IBOutlet weak var tableViewOutLet: UITableView!
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
var postContentArray = [Post]() // contine all Posts .
var userContentArray = [UserModel]()
override func viewDidLoad() {
super.viewDidLoad()
tableViewOutLet.dataSource = self
tableViewOutLet.delegate = self
tableViewOutLet.estimatedRowHeight = 521
tableViewOutLet.rowHeight = UITableView.automaticDimension
loadPosts()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.tabBar.isHidden = false
}
@objc func loadPosts () {
// activityIndicatorView.startAnimating()
API.Feed.ObserveFeedWithMyPostAndFollowerPost(withid: API.User.Curren_User!.uid) { (postr) in
self.fetchUserInfo(PostUserID: postr.userPostId!, Completed: {
self.postContentArray.append(postr)
// self.activityIndicatorView.stopAnimating()
self.tableViewOutLet.reloadData()
})
}
API.Feed.ObserveFeedReomved(withid: API.User.Curren_User!.uid) { (post) in
// print(key)
// a لحذف منشورات المستخدم من التيبل فيو
// self.postContentArray.removeLast()
self.postContentArray = self.postContentArray.filter {$0.postID != post.postID}
self.userContentArray = self.userContentArray.filter {$0.id != post.userPostId}
self.tableViewOutLet.reloadData()
}
}
@objc func fetchUserInfo (PostUserID : String , Completed : @escaping ()-> Void) {
API.User.observeUserInformation(CommentUserID: PostUserID) { (User) in
self.userContentArray.append(User)
Completed()
}
}
@IBAction func logOutButton(_ sender: Any) {
AuthServices.logout(OnSuccess: {
SVProgressHUD.showSuccess(withStatus: "تم تسجيل الخروج")
let storyBoard = UIStoryboard(name: "Start", bundle: nil)
let signInvc = storyBoard.instantiateViewController(withIdentifier: "SignInVC")
self.present(signInvc, animated: true, completion: nil)
}) { (error) in
SVProgressHUD.showError(withStatus: error)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "commentIconSequeToCommentPage" {
let commentvc = segue.destination as! CommentsVC
commentvc.postID = sender as? String
}
if segue.identifier == "Home_ToUserProfileTappedVC" {
let userid = segue.destination as! UserProfileTappedVC
userid.userID = sender as! String
}
}
}
extension HomeVC: UITableViewDataSource , UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postContentArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! HomeTableViewCell
let postContent = postContentArray[indexPath.row]
let userContent = userContentArray[indexPath.row]
cell.postContent = postContent
cell.userContentInfo = userContent
// l لتفعيل زر الردود و مساواته بالمتغير هوم فيو الموجود في ملف هوم تيبل فيو سيل
cell.homeView = self
cell.delegate = self
return cell
}
}
extension HomeVC : HomeTableViewCellDelegate {
func GoToUserProfileTappedVC(id: String) {
performSegue(withIdentifier: "Home_ToUserProfileTappedVC", sender: id)
}
func GoToCommentVC(postID: String) {
performSegue(withIdentifier: "commentIconSequeToCommentPage", sender: postID)
}
}