使用 Swift 和 Parse 创建图像预览
Creating Image Preview using Swift and Parse
我目前正在 Swift 中编写社交网络应用程序。在我的应用程序中,我有一个功能,即用户可以将带有图像的消息发送到时间轴。我希望能够检索图像并使用我的时间线内的 UIImageView 预览它。但是,我希望图像显示在发送图像的用户旁边,如果用户没有 post 图像,则图像预览不会与消息一起显示。我想要的功能的一个很好的例子是 Facebook 和 Twitter 在各自的 iOS 应用程序中显示图像的方式。与此同时,我编写了以下函数来检索图像,但我无法将它们与正确的用户匹配。我将在下面 posted 以及 link 将源代码下载到我的时间线。提前致谢
func loadImages()
{
var query = PFQuery(className: "imagesUploaded")
query.orderByDescending("objectId")
query.whereKey("user", equalTo:PFUser.currentUser())
query.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]!,error:NSError!) -> Void in
if error == nil {
let imagesobjects = objects as [PFObject]
for object : PFObject in objects as [PFObject] {
let image = object["filename"] as PFFile
image.getDataInBackgroundWithBlock {
(imageData:NSData!, error:NSError!) -> Void in
if error == nil {
if let finalimage = UIImage(data: imageData)
{
let url = image.url
println(url)
cell.imagedisplay.image = finalimage
}
}
}
}
}
}
}
我用这个 class :
import UIKit
import Parse
class postViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var photoSelected:Bool = false
var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
@IBOutlet weak var imageToPost: UIImageView!
@IBOutlet weak var shareText: UITextField!
@IBAction func logout(sender: AnyObject) {
PFUser.logOut()
self.performSegueWithIdentifier("logout", sender: "self")
}
@IBAction func chooseImage(sender: AnyObject) {
// Creation d'une variable image controlleur
var image = UIImagePickerController()
dispatch_async(dispatch_get_main_queue()){
image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
image.allowsEditing = false
self.presentViewController(image, animated: true, completion: nil)}
}
@IBAction func postImage(sender: AnyObject) {
var error = ""
if (photoSelected == false){
error = "Please Select an Image to post"
} else if (shareText.text == "") {
error = "Please enter a message"
}
if (error != ""){
displayAlert("Cannot post Image", error: error)
} else {
activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))
// On positione l'indicateur au centre de l'ecran
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
var post = PFObject(className: "post")
post["Title"] = shareText.text
post["username"] = PFUser.currentUser().username
post.saveInBackgroundWithBlock{(success: Bool, error: NSError!) -> Void in
if success == false {
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
self.displayAlert("Could not post Image", error: "Please try again later")
} else {
let imageData = UIImagePNGRepresentation(self.imageToPost.image)
let imageFile = PFFile(name: "image.png", data: imageData)
post["imageFile"] = imageFile
post.saveInBackgroundWithBlock{(success: Bool, error: NSError!) -> Void in
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if success == false {
self.displayAlert("Could not post Image", error: "Please try again later")
} else {
self.displayAlert(" Image Posted !", error: "Your image has been posted successfully")
self.photoSelected = false
self.imageToPost.image = UIImage(named: "default-placeholder")
self.shareText.text = ""
println("Posted succesfully")
}
}
}
}
}
}
func displayAlert(title: String, error: String){
var alert = UIAlertController(title: title, message: error, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: {action in
}))
self.presentViewController(alert, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
println("Image is selected!")
self.dismissViewControllerAnimated(true, completion: nil)
imageToPost.image = image
photoSelected = true
}
override func viewDidLoad() {
super.viewDidLoad()
photoSelected = false
imageToPost.image = UIImage(named: "default-placeholder")
self.shareText.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)
}
func textFiledShouldReturn(textField: UITextField!) -> Bool{
shareText.resignFirstResponder()
return true
}
}
编辑:
您可以像这样添加测试:
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
self.dismissViewControllerAnimated(true, completion: nil)
initialisationPhoto()
photoUtilisateur.image = image
if (photoUtilisateur.image != nil){
println("Image is selected!")
photoSelected = true
}
}
func initialisationPhoto(){
//Initialisation de la photo utilisateur
photoSelected = false
photoUtilisateur.image = UIImage(named: "placeholder")
}
我目前正在 Swift 中编写社交网络应用程序。在我的应用程序中,我有一个功能,即用户可以将带有图像的消息发送到时间轴。我希望能够检索图像并使用我的时间线内的 UIImageView 预览它。但是,我希望图像显示在发送图像的用户旁边,如果用户没有 post 图像,则图像预览不会与消息一起显示。我想要的功能的一个很好的例子是 Facebook 和 Twitter 在各自的 iOS 应用程序中显示图像的方式。与此同时,我编写了以下函数来检索图像,但我无法将它们与正确的用户匹配。我将在下面 posted 以及 link 将源代码下载到我的时间线。提前致谢
func loadImages()
{
var query = PFQuery(className: "imagesUploaded")
query.orderByDescending("objectId")
query.whereKey("user", equalTo:PFUser.currentUser())
query.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]!,error:NSError!) -> Void in
if error == nil {
let imagesobjects = objects as [PFObject]
for object : PFObject in objects as [PFObject] {
let image = object["filename"] as PFFile
image.getDataInBackgroundWithBlock {
(imageData:NSData!, error:NSError!) -> Void in
if error == nil {
if let finalimage = UIImage(data: imageData)
{
let url = image.url
println(url)
cell.imagedisplay.image = finalimage
}
}
}
}
}
}
}
我用这个 class :
import UIKit
import Parse
class postViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var photoSelected:Bool = false
var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
@IBOutlet weak var imageToPost: UIImageView!
@IBOutlet weak var shareText: UITextField!
@IBAction func logout(sender: AnyObject) {
PFUser.logOut()
self.performSegueWithIdentifier("logout", sender: "self")
}
@IBAction func chooseImage(sender: AnyObject) {
// Creation d'une variable image controlleur
var image = UIImagePickerController()
dispatch_async(dispatch_get_main_queue()){
image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
image.allowsEditing = false
self.presentViewController(image, animated: true, completion: nil)}
}
@IBAction func postImage(sender: AnyObject) {
var error = ""
if (photoSelected == false){
error = "Please Select an Image to post"
} else if (shareText.text == "") {
error = "Please enter a message"
}
if (error != ""){
displayAlert("Cannot post Image", error: error)
} else {
activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))
// On positione l'indicateur au centre de l'ecran
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
var post = PFObject(className: "post")
post["Title"] = shareText.text
post["username"] = PFUser.currentUser().username
post.saveInBackgroundWithBlock{(success: Bool, error: NSError!) -> Void in
if success == false {
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
self.displayAlert("Could not post Image", error: "Please try again later")
} else {
let imageData = UIImagePNGRepresentation(self.imageToPost.image)
let imageFile = PFFile(name: "image.png", data: imageData)
post["imageFile"] = imageFile
post.saveInBackgroundWithBlock{(success: Bool, error: NSError!) -> Void in
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if success == false {
self.displayAlert("Could not post Image", error: "Please try again later")
} else {
self.displayAlert(" Image Posted !", error: "Your image has been posted successfully")
self.photoSelected = false
self.imageToPost.image = UIImage(named: "default-placeholder")
self.shareText.text = ""
println("Posted succesfully")
}
}
}
}
}
}
func displayAlert(title: String, error: String){
var alert = UIAlertController(title: title, message: error, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: {action in
}))
self.presentViewController(alert, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
println("Image is selected!")
self.dismissViewControllerAnimated(true, completion: nil)
imageToPost.image = image
photoSelected = true
}
override func viewDidLoad() {
super.viewDidLoad()
photoSelected = false
imageToPost.image = UIImage(named: "default-placeholder")
self.shareText.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)
}
func textFiledShouldReturn(textField: UITextField!) -> Bool{
shareText.resignFirstResponder()
return true
}
}
编辑:
您可以像这样添加测试:
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
self.dismissViewControllerAnimated(true, completion: nil)
initialisationPhoto()
photoUtilisateur.image = image
if (photoUtilisateur.image != nil){
println("Image is selected!")
photoSelected = true
}
}
func initialisationPhoto(){
//Initialisation de la photo utilisateur
photoSelected = false
photoUtilisateur.image = UIImage(named: "placeholder")
}