将图像从UIImageView上传到Parse.com

时间:2015-09-16 21:58:39

标签: ios swift parse-platform

我正在尝试使用图片文本将图片上传到Parse.com,为上传图片的人上传时间和用户名,有时它可以正常工作,但大部分时间都不起作用。

enter image description here

正如你可以看到它上面写着“uploaded_image.png”,它成功上传了图片的所有内容,但是在顶部的行上,图片没有上传。

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

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

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
    }
}

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

  

快照未渲染的视图会导致空白   快照。确保您的视图至少在之前呈现过一次   屏幕更新后的快照或快照。

有什么建议在这做什么?代码应该如何?

1 个答案:

答案 0 :(得分:0)

我发现图像文件在通过蜂窝数据而不是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];
    ...
    ...
    ...
    }
}