PFFile 大小问题与 parse 和 swift

Posted

技术标签:

【中文标题】PFFile 大小问题与 parse 和 swift【英文标题】:PFFile size issues with parse and swift 【发布时间】:2015-06-22 22:11:06 【问题描述】:

为什么我在 iphone 上拍摄的一些照片太大而无法上传,无法解析为 PFFile。限制是 10 mgb,我知道这些图片不可能那么大。有些足够小,但大多数不是。反正有没有优化解析的大小?这是我的代码

//--CONTROLS HOW TO PICK THE IMAGE WHEN THIS BUTTON IS CLICKED--\\
@IBAction func chooseImage(sender: AnyObject) 
    var image = UIImagePickerController()
    image.delegate = self
    image.navigationBar.tintColor = UIColor.whiteColor()
    image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    image.allowsEditing = false
    self.presentViewController(image, animated: true, completion: nil)



   @IBAction func postImage(sender: AnyObject) 
    self.view.endEditing(true)
    var error = ""
    if photoSelected == false
        error="Please select an image to post."
    
    else if contactText.text == ""
        error = "Please enter an email or phone number."
    
    else if nameOfPost.text == ""
        error="Please enter the name of the post."
    
    else if descriptionOfPost.text == ""
        error="Please enter a description about your posts."
    

    if error != ""
        displayAlert("Oops! There was an error with posting.", error: error)
    
    else
        activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 125, 125))
        activityIndicator.center = self.view.center
        activityIndicator.hidesWhenStopped = true
        activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
        activityIndicator.backgroundColor = UIColor(red: (158/255.0), green: (40/255.0), blue: (52/255.0), alpha: 1)
        activityIndicator.layer.cornerRadius = 10
        view.addSubview(activityIndicator)
        activityIndicator.startAnimating()
        UIApplication.sharedApplication().beginIgnoringInteractionEvents()

//--MAIN CODE TO POST--\\
        var post  = PFObject(className: "Posts")
        post["Contact"] = contactText.text
        post["Name"] = nameOfPost.text
        post["Description"] = descriptionOfPost.text
        let imageData = UIImagePNGRepresentation(self.imageToPost.image)
        let imageFile = PFFile(name: "image.png", data: imageData)
        post["imageFile"] = imageFile
        post["createdBy"] = PFUser.currentUser()?.objectId


        //--GETTING LOCATION OF THE POST--\\
        PFGeoPoint.geoPointForCurrentLocationInBackground 
            (geoPoint: PFGeoPoint?, error: NSError?) -> Void in
            if error == nil 
                post.setValue(geoPoint, forKey: "Location")
                post.saveInBackground()
                println("found location")
            
        

        //--SAVING THE Post HERE--\\
        post.saveInBackgroundWithBlock(success:Bool, error:NSError?)-> Void in
            self.activityIndicator.stopAnimating()
            UIApplication.sharedApplication().endIgnoringInteractionEvents()
            if success == false
                self.activityIndicator.stopAnimating()
                UIApplication.sharedApplication().endIgnoringInteractionEvents()
                self.displayAlert("Sorry! We could not post.", error: "Please try again later.")
            
//--NO ERRORS SO NOW WE CAN SAVE AND POST==\\
            else
                self.performSegueWithIdentifier("backToFeed", sender: self)

            

        
    


我确实需要能够为我的应用拍照,但我从相机拍摄的每张照片都太大了。

【问题讨论】:

您可以在保存到 Parse 之前调整图像大小。 我将如何去做。这是用户驱动的 google.com/… 其余代码在哪里?什么是帖子? post 是 parse 中的一个类 【参考方案1】:

你的代码对我来说有点小鱼,我会这样做:

var post:PFObject

func prepareToSavePost()
    post  = PFObject(className: "Posts")
    post["Contact"] = contactText.text
    post["Name"] = nameOfPost.text
    post["Description"] = descriptionOfPost.text
    let imageData = UIImagePNGRepresentation(self.imageToPost.image)
    let imageFile = PFFile(name: "image.png", data: imageData)
    post["imageFile"] = imageFile
    post["createdBy"] = PFUser.currentUser()?.objectId

    //Get bytes size of image
    var imageSize = Float(imageData.length)
    //Transform into Megabytes
    imageSize = imageSize/(1024*1024)
    println("Image size is \(imageSize)Mb")

    PFGeoPoint.geoPointForCurrentLocationInBackground 
        (geoPoint: PFGeoPoint?, error: NSError?) -> Void in
        if error == nil 
            self.post.setValue(geoPoint, forKey: "Location")
            println("found location")
            savePost()
        
    


func savePost()
    post.saveInBackgroundWithBlock
        (success:Bool, error:NSError?)-> Void in
                self.activityIndicator.stopAnimating()
                UIApplication.sharedApplication().endIgnoringInteractionEvents()
                if success == false
                    self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
                    self.displayAlert("Sorry! We could not post.", error: "Please try again later.")
                
    //--NO ERRORS SO NOW WE CAN SAVE AND POST==\\
                else
                    self.performSegueWithIdentifier("backToFeed", sender: self)
                
        
    

为什么我会那样做?您似乎可以在尝试同时更新位置和其他详细信息时陷入死锁,换句话说,在后台并行运行两次保存命令。

这会解决您的问题吗?也许,parse.com 并不总是按实际情况发送错误

我还为图像大小添加了一个日志,但您可以在 if 中对其进行转换并弹出警报视图,或者如果图像大于 10Mb 则调整图像大小(我认为 iPhone 不会发生这种情况)

【讨论】:

表示pffile没有length的成员。在这一行找到var imageSize = Float(imageFile.length) @user2967062 抱歉应该是 imageData 而不是 imageFile,我已经更新了答案 没问题。它还提到了不能在另一个本地函数中使用本地函数

以上是关于PFFile 大小问题与 parse 和 swift的主要内容,如果未能解决你的问题,请参考以下文章

减少 Parse PFFile、图像和文本

Parse - imageView as PFFile 不会加载

如何限制 PFFile 的后台下载 - Parse Framework

在 iOS 上使用 Parse BaaS:我应该使用 PFFile 来保存原始类型和 Objective-C 类吗?

从 Parse 将 PFFile 转换为 NSData

PFFile 无法将文件存储到 Parse-server