Asynchronous Request (Order Matters) - asynchronous

I'm using Alamofire to execute a number of asynchronous requests concurrently, and SwiftyJSON to handle the response.
I need help making sure that appending to moviesByCategory occurs in order.
For example, the "top_rated" data response should be the first element appended to moviesByCategory, not "upcoming".
var moviesByCategory = [[JSON]]()
override func viewDidLoad() {
super.viewDidLoad()
let apiEndPoints = ["top_rated", "popular", "now_playing", "upcoming"]
let dispatchGroup = DispatchGroup()
for endPoint in apiEndPoints {
let endPointURL = URL(string: "https://api.themoviedb.org/3/movie/\(endPoint)?api_key=\(apiKey)&language=en-US&page=1")!
dispatchGroup.enter()
getMoviesFromEndPoint(url: endPointURL)
}
dispatchGroup.notify(queue: DispatchQueue.main) {
self.tableView.reloadData()
}
}
func getMoviesFromEndPoint(url: URL, group: dispatchGroup) {
Alamofire.request(url).responseData { response in
if let data = response.result.value {
let json = JSON(data: data)
self.moviesByCategory.append(json["results"].arrayValue)
}
}
}
The purpose for DispatchGroup is to reload the UITableView once all requests have completed.
Any help with this would be tremendously appreciated. Please do point out where I am wrong.

Add a completion handler parameter to getMoviesFromEndPoint:
func getMoviesFromEndPoint(url: URL, completion: () -> Void) { ... }
and leave the group within after the network call completed:
getMoviesFromEndPoint(url: endPointURL) {
dispatchGroup.leave()
}
Complete code:
override func viewDidLoad() {
super.viewDidLoad()
let apiEndPoints = ["top_rated", "popular", "now_playing", "upcoming"]
let dispatchGroup = DispatchGroup()
for endPoint in apiEndPoints {
let endPointURL = URL(string: "https://api.themoviedb.org/3/movie/\(endPoint)?api_key=\(apiKey)&language=en-US&page=1")!
dispatchGroup.enter()
getMoviesFromEndPoint(url: endPointURL) {
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: DispatchQueue.main) {
self.tableView.reloadData()
}
}
func getMoviesFromEndPoint(url: URL, completion: () -> Void) {
Alamofire.request(url).responseData { response in
if let data = response.result.value {
let json = JSON(data: data)
self.moviesByCategory.append(json["results"].arrayValue)
}
completion()
}
}

Related

Cannot infer an appropriate lifetime for self "required to be static"

I am prototyping channel based system and when converting code to use async tasks, I came across the error that &mut self needs to have an appropriate lifetime.
I have tried setting the &mut self to &'static self but that does not work. I have tried to wrap the entire code in an async block returning Future<Output=()> + 'static which also did not work.
Here is the code:
struct RequestManager {
connection_state: ConnectionState,
backoff: u64,
exponent: u32,
maximum: u64,
}
impl RequestManager {
async fn run(&mut self, mut feed_queue: Receiver<FeedItem>) {
let (mut fetch_result_sender, mut fetch_result_receiver) = channel(5);
let (mut fetch_request_sender, mut fetch_request_receiver) = channel::<FeedItem>(5);
let request_sender = mpsc::Sender::clone(&fetch_result_sender);
tokio::spawn(async move {
loop {
match self.connection_state {
ConnectionState::Closed => {
while let Some(feed) = fetch_request_receiver.recv().await {
let mut request_sender = mpsc::Sender::clone(&request_sender);
tokio::spawn(async move {
let response = make_request(&feed.feed_address).await;
if let Err(_) = response {
self.connection_state =
ConnectionState::HalfOpen(feed.feed_address);
} else {
let response = read_response_body(response.unwrap()).await;
let result = FetchResult { body: response };
if let Err(e) = request_sender.send(result).await {
eprintln!("could not send fetch result: {}", e);
}
}
});
}
}
ConnectionState::HalfOpen(url) => {
let response = make_request(&url).await;
if let Err(_) = response {
self.connection_state = ConnectionState::Open(url);
} else {
let response = read_response_body(response.unwrap()).await;
let result = FetchResult { body: response };
// // TODO: sends to task/feedService
connection_state = ConnectionState::Closed;
if let Err(e) = fetch_result_sender.send(result).await {
eprintln!("could not send fetch result: {}", e);
}
}
}
ConnectionState::Open(url) => {
let new_backoff = calculate_backoff();
delay_for(Duration::from_secs(new_backoff));
self.connection_state = ConnectionState::HalfOpen(url)
}
}
}
});
}
}

Cant Create Accout (Upload Image Swift)

After importing Firebase to my Project which i want to Create for iOS (Swift)
I tried to create a user, with ProfileImage and Username.
When i tap "Create Account" i get an error message it says "Error signing up".
This is the Error Message in the Terminal
2018-07-20 23:15:50.764062+0200 Collect App[3341:120860] [discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}
I will paste my code here.
//
// SignUpViewController.swift
import Foundation
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage
class SignUpViewController: UIViewController {
#IBOutlet weak var userNameTextField: UITextField!
#IBOutlet weak var userEmailTextField: UITextField!
#IBOutlet weak var userPasswordTextField: UITextField!
#IBOutlet weak var confirmuserPasswordTextField: UITextField!
#IBOutlet weak var profileImageView: UIImageView!
#IBOutlet weak var dismissButton: UIButton!
#IBAction func tapToChangeProfileButton(_ sender: Any) {
}
#IBAction func handleDismissButton(_ sender: Any) {
self.dismiss(animated: false, completion: nil)
}
var imagePicker:UIImagePickerController!
private var authUser : User? {
return Auth.auth().currentUser
}
public func sendVerificationMail() {
if self.authUser != nil && !self.authUser!.isEmailVerified {
self.authUser!.sendEmailVerification(completion: { (error) in
// Notify the user that the mail has sent or couldn't because of an error.
})
}
else {
// Either the user is not available, or the user is already verified.
}
}
override func viewDidLoad() {
super.viewDidLoad()
let imageTap = UITapGestureRecognizer(target: self, action: #selector(openImagePicker))
profileImageView.isUserInteractionEnabled = true
profileImageView.addGestureRecognizer(imageTap)
profileImageView.layer.cornerRadius = profileImageView.bounds.height / 2
profileImageView.clipsToBounds = true
//tapToChangeProfileButton.addTarget(self, action: #selector(openImagePicker), for: .touchUpInside)
imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#objc func openImagePicker(_ sender:Any) {
// Open Image Picker
self.present(imagePicker, animated: true, completion: nil)
}
#IBAction func CreateAccount(_ sender: Any) {
guard let username = userNameTextField.text else { return }
guard let email = userEmailTextField.text else { return }
guard let pass = userPasswordTextField.text else { return }
guard let image = profileImageView.image else { return }
Auth.auth().createUser(withEmail: email, password: pass) { user, error in
if error == nil && user != nil {
print("User created!")
// 1. Upload the profile image to Firebase Storage
self.uploadProfileImage(image) { url in
if url != nil {
let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.displayName = username
changeRequest?.photoURL = url
changeRequest?.commitChanges { error in
if error == nil {
print("User display name changed!")
self.saveProfile(username: username, profileImageURL: url!) { success in
if success {
self.dismiss(animated: true, completion: nil)
} else {
self.resetForm()
}
}
} else {
print("Error: \(error!.localizedDescription)")
self.resetForm()
}
}
} else {
self.resetForm()
}
}
} else {
self.resetForm()
}
}
}
func resetForm() {
let alert = UIAlertController(title: "Error signing up", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func uploadProfileImage(_ image:UIImage, completion: #escaping ((_ url:URL?)->())) {
guard let uid = Auth.auth().currentUser?.uid else { return }
let storageRef = Storage.storage().reference().child("user/\(uid)")
// Create a reference to the file you want to download
let starsRef = storageRef.child("images/stars.jpg")
// Fetch the download URL
starsRef.downloadURL { url, error in
if let error = error {
// Handle any errors
} else {
// Get the download URL for 'images/stars.jpg'
}
}
}
func saveProfile(username:String, profileImageURL:URL, completion: #escaping ((_ success:Bool)->())) {
guard let uid = Auth.auth().currentUser?.uid else { return }
let databaseRef = Database.database().reference().child("users/profile/\(uid)")
let userObject = [
"username": username,
"photoURL": profileImageURL.absoluteString
] as [String:Any]
databaseRef.setValue(userObject) { error, ref in
completion(error == nil)
}
}
#IBAction func AlreadyaccountButtonTapped(_ sender: Any) {
print("Already account Button Tapped")
let LoginViewController = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
self.present(LoginViewController, animated: true)
}
//EmailVerificationViewController
#IBAction func ResendEmailVerificationTapped(_ sender: Any) {
self.sendVerificationMail()
}
#IBAction func LoginButtonTapped(_ sender: Any) {
print("Login Button Tapped")
let LoginViewController = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
self.present(LoginViewController, animated: true)
}
func displayMessage(userMessage:String) -> Void {
DispatchQueue.main.async
{
let alertController = UIAlertController(title: "Alert", message: userMessage, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
// Code in this block will trigger when OK button tapped.
print("Ok button tapped")
DispatchQueue.main.async
{
self.dismiss(animated: true, completion: nil)
}
}
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion:nil)
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
}
}
extension SignUpViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
self.profileImageView.image = pickedImage
}
picker.dismiss(animated: true, completion: nil)
}
}
Thanks for your time !
Now the New Code with another i error that i mentioned in the Comment
#IBAction func CreateAccount(_ sender: Any) {
guard let username = userNameTextField.text else { return }
guard let image = profileImageView.image else { return }
Auth.auth().createUser(withEmail: self.userEmailTextField.text!, password: self.userPasswordTextField.text!) { user, error in
if error == nil && user != nil {
print("User created!")
// 1. Upload the profile image to Firebase Storage
self.uploadProfileImage(image, uid: user.uid) { url in
if url != nil {
let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.displayName = username
changeRequest?.photoURL = url
changeRequest?.commitChanges { error in
if error == nil {
print("User display name changed!")
self.saveProfile(username: username, profileImageURL: url!) { success in
if success {
self.dismiss(animated: true, completion: nil)
} else {
self.resetForm()
}
}
} else {
print("Error: \(error!.localizedDescription)")
self.resetForm()
}
}
} else {
self.resetForm()
}
}
} else {
self.resetForm()
}
}
}
func resetForm() {
let alert = UIAlertController(title: "Error signing up", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func uploadProfileImage(_ image:UIImage, uid:String, completion: #escaping ((_ url:URL?)->())) {
let storageRef = Storage.storage().reference().child("user/\(uid)")
// Create a reference to the file you want to download
let starsRef = storageRef.child("images/stars.jpg")
// Fetch the download URL
starsRef.downloadURL { url, error in
if let error = error {
// Handle any errors
} else {
// Get the download URL for 'images/stars.jpg'
}
}
}
You are getting that error because your url is nil.
It is nil because you are creating the user, upon successful creation self.uploadProfileImage(image) is called in order to get the image url of the current user but the user is not logged in.
A solution would be:
Sign in the user and upon success then call uploadProfileImage.

NSError * domain: #"com.google.HTTPStatus" - code: 404

I am trying to read images from Firebase storage, and I am getting this error:
NSError * domain: #"com.google.HTTPStatus" - code: 404
In function:
- (void)invokeFetchCallbacksOnCallbackQueueWithData:(GTM_NULLABLE NSData *)data
error:(GTM_NULLABLE NSError *)error {
// Callbacks will be released in the method stopFetchReleasingCallbacks:
GTMSessionFetcherCompletionHandler handler;
#synchronized(self) {
GTMSessionMonitorSynchronized(self);
handler = _completionHandler;
if (handler) {
[self invokeOnCallbackQueueUnlessStopped:^{
handler(data, error);
// Post a notification, primarily to allow code to collect responses for
// testing.
//
// The observing code is not likely on the fetcher's callback
// queue, so this posts explicitly to the main queue.
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
if (data) {
userInfo[kGTMSessionFetcherCompletionDataKey] = data;
}
if (error) {
userInfo[kGTMSessionFetcherCompletionErrorKey] = error;
}
[self postNotificationOnMainThreadWithName:kGTMSessionFetcherCompletionInvokedNotification
userInfo:userInfo
requireAsync:NO];
}];
}
} // #synchronized(self)
This is my code for reading from Firebase Storage:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "product_collection_cell", for: indexPath) as! ProductsCollectionViewCell
let prodInCell = searchActive ? filtered[indexPath.row] : products[indexPath.row]
// Set fields
cell.ProductImageView.image = #imageLiteral(resourceName: "DefaultProductImage")
prodInCell.GetProductImage() { image in
cell.ProductImageView.image = image
}
cell.ProductName.text = prodInCell.Name()
cell.ProductPrice.text = String(prodInCell.Price())
cell.productUniqueID = prodInCell.UniqueID()
return cell
}
public func GetProductImage(completion: ((UIImage?) -> Void)) {
let prodID = self.UniqueID()
let dbRef = Storage.storage().reference().child(prodID).child("pic0.jpg")
let imgTask = dbRef.getData(maxSize: 10*1024*1024, completion: { (data, error) in
if let data = data, let img = UIImage(data: data) {
completion(img)
} else {
completion(nil)
}
})
imgTask.observe(.progress, handler: {(snapshot) in
print (snapshot.progress ?? "NO MORE PROGRESS")
})
imgTask.resume()
}
And I get exception: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10)
What is the problem and how can I resolve this ?
Not all my products have images, and if one does not I want to display "DefaultProductImage".
This is an example of one of my products' images stored:

Why incoming message can't show in the left side of the screen?

I got some error when I send photo message.
I'm a beginner with swift language. I want to create undergraduate project about chat app. I need some help to fix this problem. Everything had worked smoothly till now but I am facing a small bug that is when I receive an image then it don't appears on the left side of the screen both incoming and outgoing images appear on the right side of the screen.
import UIKit
import JSQMessagesViewController
import MobileCoreServices
import AVKit
import FirebaseDatabase
import FirebaseStorage
import FirebaseAuth
import SDWebImage
class ChatViewController: JSQMessagesViewController {
var messages = [JSQMessage]()
var avatarDict = [String: JSQMessagesAvatarImage]()
var messageRef = FIRDatabase.database().reference().child("messages")
override func viewDidLoad() {
super.viewDidLoad()
if let currentUser = FIRAuth.auth()?.currentUser
{
self.senderId = currentUser.uid
if currentUser.isAnonymous == true
{
self.senderDisplayName = "anonymous"
} else
{
self.senderDisplayName = "\(currentUser.displayName!)"
}
}
observeMessages()
}
func observeUsers(_ id: String)
{
FIRDatabase.database().reference().child("users").child(id).observe(.value, with: {
snapshot in
if let dict = snapshot.value as? [String: AnyObject]
{
let avatarUrl = dict["profileUrl"] as! String
self.setupAvatar(avatarUrl, messageId: id)
}
})
}
func setupAvatar(_ url: String, messageId: String)
{
if url != "" {
let fileUrl = URL(string: url)
let data = try? Data(contentsOf: fileUrl!)
let image = UIImage(data: data!)
let userImg = JSQMessagesAvatarImageFactory.avatarImage(with: image, diameter: 30)
self.avatarDict[messageId] = userImg
self.collectionView.reloadData()
} else {
avatarDict[messageId] = JSQMessagesAvatarImageFactory.avatarImage(with: UIImage(named: "profileImage"), diameter: 30)
collectionView.reloadData()
}
}
func observeMessages() {
messageRef.observe(.childAdded, with: { snapshot in
// print(snapshot.value)
if let dict = snapshot.value as? [String: AnyObject] {
let mediaType = dict["MediaType"] as! String
let senderId = dict["senderId"] as! String
let senderName = dict["senderName"] as! String
self.observeUsers(senderId)
switch mediaType {
case "TEXT":
let text = dict["text"] as! String
self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, text: text))
case "PHOTO":
let photo = JSQPhotoMediaItem(image: nil)
let fileUrl = dict["fileUrl"] as! String
let downloader = SDWebImageDownloader.shared()
downloader.downloadImage(with: URL(string: fileUrl)!, options: [], progress: nil, completed: { (image, data, error, finished) in
DispatchQueue.main.async(execute: {
photo?.image = image
self.collectionView.reloadData()
})
})
self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, media: photo))
if self.senderId == senderId {
photo?.appliesMediaViewMaskAsOutgoing = true
} else {
photo?.appliesMediaViewMaskAsOutgoing = false
}
case "VIDEO":
let fileUrl = dict["fileUrl"] as! String
let video = URL(string: fileUrl)!
let videoItem = JSQVideoMediaItem(fileURL: video, isReadyToPlay: true)
self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, media: videoItem))
if self.senderId == senderId {
videoItem?.appliesMediaViewMaskAsOutgoing = true
} else {
videoItem?.appliesMediaViewMaskAsOutgoing = false
}
default:
print("unknown data type")
}
self.collectionView.reloadData()
}
})
}
override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) {
let newMessage = messageRef.childByAutoId()
let messageData = ["text": text, "senderId": senderId, "senderName": senderDisplayName, "MediaType": "TEXT"]
newMessage.setValue(messageData)
self.finishSendingMessage()
}
override func didPressAccessoryButton(_ sender: UIButton!) {
print("didPressAccessoryButton")
let sheet = UIAlertController(title: "Media Messages", message: "Please select a media", preferredStyle: UIAlertControllerStyle.actionSheet)
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (alert:UIAlertAction) in
}
let photoLibrary = UIAlertAction(title: "Photo Library", style: UIAlertActionStyle.default) { (alert: UIAlertAction) in
self.getMediaFrom(kUTTypeImage)
}
let videoLibrary = UIAlertAction(title: "Video Library", style: UIAlertActionStyle.default) { (alert: UIAlertAction) in
self.getMediaFrom(kUTTypeMovie)
}
sheet.addAction(photoLibrary)
sheet.addAction(videoLibrary)
sheet.addAction(cancel)
self.present(sheet, animated: true, completion: nil)
}
func getMediaFrom(_ type: CFString) {
print(type)
let mediaPicker = UIImagePickerController()
mediaPicker.delegate = self
mediaPicker.mediaTypes = [type as String]
self.present(mediaPicker, animated: true, completion: nil)
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! {
return messages[indexPath.item]
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! {
let message = messages[indexPath.item]
let bubbleFactory = JSQMessagesBubbleImageFactory()
if message.senderId == self.senderId {
return bubbleFactory!.outgoingMessagesBubbleImage(with: .black)
} else {
return bubbleFactory!.incomingMessagesBubbleImage(with: .blue)
}
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {
let message = messages[indexPath.item]
return avatarDict[message.senderId]
//return JSQMessagesAvatarImageFactory.avatarImageWithImage(UIImage(named: "profileImage"), diameter: 30)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("number of item:\(messages.count)")
return messages.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell
return cell
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, didTapMessageBubbleAt indexPath: IndexPath!) {
print("didTapMessageBubbleAtIndexPath: \(indexPath.item)")
let message = messages[indexPath.item]
if message.isMediaMessage {
if let mediaItem = message.media as? JSQVideoMediaItem {
let player = AVPlayer(url: mediaItem.fileURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true, completion: nil)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func logoutDidTapped(_ sender: AnyObject) {
do {
try FIRAuth.auth()?.signOut()
} catch let error {
print(error)
}
// Create a main storyboard instance
let storyboard = UIStoryboard(name: "Main", bundle: nil)
// From main storyboard instantiate a View controller
let LogInVC = storyboard.instantiateViewController(withIdentifier: "LogInVC") as! LogInViewController
// Get the app delegate
let appDelegate = UIApplication.shared.delegate as! AppDelegate
// Set LogIn View Controller as root view controller
appDelegate.window?.rootViewController = LogInVC
}
func sendMedia(_ picture: UIImage?, video: URL?) {
print(picture)
print(FIRStorage.storage().reference())
if let picture = picture {
let filePath = "\(FIRAuth.auth()!.currentUser)/\(Date.timeIntervalSinceReferenceDate)"
print(filePath)
let data = UIImageJPEGRepresentation(picture, 0.1)
let metadata = FIRStorageMetadata()
metadata.contentType = "image/jpg"
FIRStorage.storage().reference().child(filePath).put(data!, metadata: metadata) { (metadata, error)
in
if error != nil {
print(error?.localizedDescription)
return
}
let fileUrl = metadata!.downloadURLs![0].absoluteString
let newMessage = self.messageRef.childByAutoId()
let messageData = ["fileUrl": fileUrl, "senderId": self.senderId, "senderName": self.senderDisplayName, "MediaType": "PHOTO"]
newMessage.setValue(messageData)
}
} else if let video = video {
let filePath = "\(FIRAuth.auth()!.currentUser)/\(Date.timeIntervalSinceReferenceDate)"
print(filePath)
let data = try? Data(contentsOf: video)
let metadata = FIRStorageMetadata()
metadata.contentType = "video/mp4"
FIRStorage.storage().reference().child(filePath).put(data!, metadata: metadata) { (metadata, error)
in
if error != nil {
print(error?.localizedDescription)
return
}
let fileUrl = metadata!.downloadURLs![0].absoluteString
let newMessage = self.messageRef.childByAutoId()
let messageData = ["fileUrl": fileUrl, "senderId": self.senderId, "senderName": self.senderDisplayName, "MediaType": "VIDEO"]
newMessage.setValue(messageData)
}
}
}
}
extension ChatViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("did finish picking")
// get the image
print(info)
if let picture = info[UIImagePickerControllerOriginalImage] as? UIImage {
sendMedia(picture, video: nil)
}
else if let video = info[UIImagePickerControllerMediaURL] as? URL {
sendMedia(nil, video: video)
}
self.dismiss(animated: true, completion: nil)
collectionView.reloadData()
}
}
You just need to understand what is going on in your code , as i am looking into your code you are reloading collectionview before the JSQPhotoMediaItem or JSQVideoMediaItem objects are completely configured and added these MediaItem into your message array, so make sure you have completely configured your JSQPhotoMediaItem and JSQVideoMediaItem objects and only after that you add these object to your message array.
you can add this into your switch case condition
case "PHOTO":
let photo = JSQPhotoMediaItem(image: nil)
let fileUrl = dict["fileUrl"] as! String
let downloader = SDWebImageDownloader.shared()
downloader.downloadImage(with: URL(string: fileUrl)!, options: [], progress: nil, completed: { (image, data, error, finished) in
DispatchQueue.main.async(execute: {
photo?.image = image // you have image in your media object
if self.senderId == senderId {
photo?.appliesMediaViewMaskAsOutgoing = true
} else {
photo?.appliesMediaViewMaskAsOutgoing = false
}
// you just configured media object by using appliesMediaViewMaskAsOutgoing
self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, media: photo))
// successfully added object into your message array now you should reload collectionview
self.collectionView.reloadData()
})
})
//same goes for your video condition
But still i would recommend you to follow each step one by one.
Follow these steps for adding A JSQPhotoMediaItem object
make a JSQPhotoMediaItem Object like
let photoItem = JSQPhotoMediaItem(image: UIImage(named: <your Image Object>))
make sure you have downloaded your image from server and successfully have your image object ready to add in the JSQPhotoMediaItem Object (as you are downloading it from firebase) first get the image then add it to your JSQPhotoMediaItem
now you have to tell your message type( outgoing or incoming ) so add appliesMediaViewMaskAsOutgoing property to according to you need so this would be in your code
if self.senderId == senderId {
photoItem?.appliesMediaViewMaskAsOutgoing = true
} else {
photoItem?.appliesMediaViewMaskAsOutgoing = false
}
now this is the final step for appending this object to your array
self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, media: photoItem))
now reload collectionView as you have successfully configured your media item ( JSQPhotoMediaItem )
self.collectionView.reloadData()
same goes for the JSQVideoMediaItem objects.

Unable to make Graph + iCloud works

what I have to write here?
db = Graph(cloud: "iCloud.com.devname.appname", completion: { (done, error) in
if let errore = error {
debugPrint("Error iCloud: \(errore.localizedDescription)")
return
}
})
or
db = Graph(cloud: "fantasyString", completion: { (done, error) in
if let errore = error {
debugPrint("Errore iCloud: \(errore.localizedDescription)")
return
}
})
I tried everything but I'm unable to make iCloud works
Thank you for your help, Daniel
EDIT:
the way I read data form db:
var customers : [Entity] {
let search = Search<Entity>(graph: db).for(types: "Customers")
return search.sync(completion: nil).sorted { ($0["name"] as! String) < ($1["name"] as! String)}
}
the way I save the record:
func newCustomer(name:String, phone:String, mail:String, closure: #escaping ()->()) {
let cliente = Entity(type: "Customers")
cliente["name"] = name
cliente["phone"] = phone
cliente["mail"] = mail
db.sync { (done, error) in
if let errore = error {
debugPrint("Errore addCustomer: \(errore.localizedDescription)")
return
}
if done { closure() }
}
}
EDIT 2: the GraphDelegate implementation:
extension DataManager: GraphDelegate {
func graphWillPrepareCloudStorage(graph: Graph, transition: GraphCloudStorageTransition) {
debugPrint("graphWillPrepareCloudStorage")
if transition == .initialImportCompleted {
debugPrint("iCloud initialImportCompleted ok")
self.clientiCont?.tableView.reloadData()
}
}
func graphDidPrepareCloudStorage(graph: Graph) {
debugPrint("graphDidPrepareCloudStorage")
self.clientiCont?.tableView.reloadData()
}
func graphWillUpdateFromCloudStorage(graph: Graph) {
debugPrint("graphWillUpdateFromCloudStorage")
self.clientiCont?.tableView.reloadData()
}
func graphDidUpdateFromCloudStorage(graph: Graph) {
debugPrint("graphDidUpdateFromCloudStorage")
// refresh clienti
self.clientiCont?.tableView.reloadData()
// refresh lista ordini
self.gestCliCont?.tableOrder.reloadData()
// refresh oridine
self.gestOrdCont?.showOrder()
self.gestOrdCont?.tableProdotti.reloadData()
}
}
EDIT: the iCloud config
Thanks to one of my students I found the bug:
if you make a record this way everything works fine:
let record = Entity(type: "Names", graph: self.db)
but if you use this init it doesn't: let record = Entity(type: "Names")
so the solution is: make a record this way
let record = Entity(type: "Names", graph: self.db)

Resources