gpt4 book ai didi

ios - 将图像从 UIImageView 上传到 Parse.com

转载 作者:行者123 更新时间:2023-11-30 14:04:07 25 4
gpt4 key购买 nike

我正在尝试将图像上传到 Parse.com,其中包含图像文本、上传时间和上传图像的人的用户名,有时它可以工作,但大多数时候它不工作。

enter image description here

正如您所看到的“uploaded_image.png”位置,它成功上传了带有图像的所有内容,但在顶部的行中,图像未上传。

看起来,当我从相机胶卷上传图像时,需要 3-5 秒,并且图像已成功上传,但是当我尝试拍照并上传此时拍摄的照片时,它不起作用..

这是我完整的UploadViewController.swift代码,希望我能得到一些提示:

import UIKit
import Parse
import Bolts
import Social
import Photos
import PhotosUI

class UploadViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {

@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var imageText: UITextField!

@IBOutlet weak var uploadingView: UIView!
@IBOutlet weak var uploadingText: UILabel!

@IBOutlet weak var uploadButton: UIButton!

var tabBarItemONE: UITabBarItem = UITabBarItem()
var tabBarItemTWO: UITabBarItem = UITabBarItem()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.imageText.delegate = self

uploadButton.backgroundColor = UIColor.clearColor()
uploadButton.layer.cornerRadius = 5
uploadButton.layer.borderWidth = 1
uploadButton.layer.borderColor = UIColor.blackColor().CGColor

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
}

override func viewDidAppear(animated: Bool) {
if (imageView.image == nil)
{
var refreshAlert = UIAlertController(title: "Message", message: "How would you like to upload a photo?.", preferredStyle: UIAlertControllerStyle.Alert)

refreshAlert.addAction(UIAlertAction(title: "Take photo", style: .Default, handler: { (action: UIAlertAction!) in
self.takePhoto()
}))

refreshAlert.addAction(UIAlertAction(title: "Choose existing photo", style: .Default, handler: { (action: UIAlertAction!) in
self.chooseExistingPhoto()
}))

refreshAlert.addAction(UIAlertAction(title: "Never mind", style: .Default, handler: { (action: UIAlertAction!) in
self.resetViewController()
self.tabBarController?.selectedIndex = 0
}))

presentViewController(refreshAlert, animated: true, completion: nil)
}

}

func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}

func keyboardWillShow(sender: NSNotification) {
self.view.frame.origin.y -= 200
}

func keyboardWillHide(sender: NSNotification) {
self.view.frame.origin.y += 200
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func uploadButtonAction(sender: AnyObject) {
self.view.endEditing(true)
uploadingView.hidden = false
uploadingText.hidden = false
uploadPost()
}
func uploadPost(){
var imageText = self.imageText.text

if (imageView.image == nil){
println("No image uploaded")
}
else{
disableTabBarItems()
var posts = PFObject(className: "Posts")
currentUploads["imageText"] = imageText
currentUploads["username"] = PFUser.currentUser()?.username
currentUploads.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
if error == nil{
//**Success saving, now save image.**//

// Create an image data
var imageData = UIImagePNGRepresentation(self.imageView.image)
// Create a parse file to store in cloud
var parseImageFile = PFFile(name: "uploaded_image.png", data: imageData)
currentUploads["imageFile"] = parseImageFile
currentUploads.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
if error == nil{
// Take user home
self.enableTabBarItems()
println(success)
println("Data uploaded")
self.resetViewController()
self.tabBarController?.selectedIndex = 0
self.showSuccessUpload()
}
else{
println(error)
}
})
}
else{
println(error)
}
})
}
}

func disableTabBarItems(){
let tabBarControllerItems = self.tabBarController?.tabBar.items

if let arrayOfTabBarItems = tabBarControllerItems as! AnyObject as? NSArray{

tabBarItemONE = arrayOfTabBarItems[0] as! UITabBarItem
tabBarItemONE.enabled = false

tabBarItemTWO = arrayOfTabBarItems[1] as! UITabBarItem
tabBarItemTWO.enabled = false

}
}

func enableTabBarItems(){
tabBarItemONE.enabled = true
tabBarItemTWO.enabled = true
}

func takePhoto(){
let picker = UIImagePickerController()

picker.delegate = self
picker.sourceType = .Camera

presentViewController(picker, animated: true, completion: nil)
}

func chooseExistingPhoto(){
let picker = UIImagePickerController()

picker.delegate = self
picker.sourceType = .PhotoLibrary

presentViewController(picker, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
imageView.image = image
let size = CGSizeApplyAffineTransform(image.size, CGAffineTransformMakeScale(0.5, 0.5))
let hasAlpha = false
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen

UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
image.drawInRect(CGRect(origin: CGPointZero, size: size))

let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
dismissViewControllerAnimated(true, completion: nil)
}

func showSuccessUpload(){
let alert = UIAlertView()
alert.title = "Message"
alert.message = "Your photo has been uploaded."
alert.addButtonWithTitle("OK")
alert.show()
}

func resetViewController(){
imageView.image = nil
imageText.text = nil
uploadingView.hidden = true
uploadingText.hidden = true
}
}

编辑:我现在在日志输出中看到,它显示某种警告:

Snapshotting a view that has not been rendered results in an empty snapshot. Ensure your view has been rendered at least once before snapshotting or snapshot after screen updates.

有什么建议吗?代码应该怎样写?

最佳答案

我发现当图像文件通过蜂窝数据而不是 WiFi 上传并且图像文件相当大时,图像文件无法可靠地更新。我将相机胶卷中的图像减少到 25%,我相信这是您的比例值。我使用 obj-c,所以我的代码看起来有点不同......

这是我的一些相关代码示例,其中注释掉了输出行,有助于比较这些图像的大小以找出合适的比例。请注意,我做的最后一件事是休眠 2 秒,以确保正确创建 imageFile。

    // For responding to the user accepting a newly-captured picture or movie
- (void) imagePickerController: (UIImagePickerController *) picker
didFinishPickingMediaWithInfo: (NSDictionary *) info
{
NSLog(@"hit use photo");
float compressionRatio = 0.25;
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToSave;

// Handle a still image capture
if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0)
== kCFCompareEqualTo)
{

editedImage = (UIImage *) [info objectForKey:
UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:
UIImagePickerControllerOriginalImage];

if (editedImage)
{
imageToSave = editedImage;
} else {
imageToSave = originalImage;
}

// Save the new image (original or edited) to the Camera Roll
UIImageWriteToSavedPhotosAlbum (imageToSave, nil, nil , nil);
imageData = UIImageJPEGRepresentation(imageToSave, compressionRatio);
// NSLog(@"imageData length after compression of 1.0: %d", [imageData length]);
// imageData = UIImageJPEGRepresentation(imageToSave, .5);
// NSLog(@"imageData length after compression of 0.5: %d", [imageData length]);
// imageData = UIImageJPEGRepresentation(imageToSave, .25);
// NSLog(@"imageData length after compression of 0.25: %d", [imageData length]);

imageFile = [PFFile fileWithName:[NSString stringWithFormat:@"completedJob%@.JPEG", _homeView.currentJob.objectId] data:imageData];
[NSThread sleepForTimeInterval:2.0];
...
...
...
}
}

关于ios - 将图像从 UIImageView 上传到 Parse.com,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32619484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com