保存照片并立即使用

时间:2015-06-17 09:46:14

标签: ios swift camera photo alamofire

我有以下代码用于拍摄照片并将其保存到相机胶卷。我需要能够在那里使用它,然后在保存后无需返回画廊并选择它。

我还没有找到任何关于如何做到这一点的例子。

    @IBOutlet weak var imagePicked: UIImageView!

    @IBAction func CameraBtn(sender: UIButton) {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
            var imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.Camera;
            imagePicker.allowsEditing = false
            self.presentViewController(imagePicker, animated: true, completion: nil)
            cameraBool = true
        }
    }

    @IBAction func GalleryBtn(sender: UIButton) {
        println("gallery button clicked")
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            var imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
            imagePicker.allowsEditing = true
            self.presentViewController(imagePicker, animated: true, completion: nil)
            cameraBool = false
        }
    }

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
        imagePicked.image = image
        if (cameraBool){
            var imageData = UIImageJPEGRepresentation(imagePicked.image, 0.6)
            var compressedJPGImage = UIImage(data: imageData)
            UIImageWriteToSavedPhotosAlbum(compressedJPGImage, nil, nil, nil)

        }
        self.dismissViewControllerAnimated(true, completion: nil);
    }

我需要能够在以下webservice函数中使用此保存的图像:

func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, String>, imageData:NSData) -> (URLRequestConvertible, NSData) {

        // create url request to send
        var mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
        mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
        let boundaryConstant = "myRandomBoundary12345";
        let contentType = "multipart/form-data;boundary="+boundaryConstant
        mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")



        // create upload data to send
        let uploadData = NSMutableData()

        // add image
        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Disposition: form-data; name=\"file\"; filename=\"file.png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData(imageData)

        // add parameters
        for (key, value) in parameters {
            uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
            uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
        }
        uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)



        // return URLRequestConvertible and NSData
        return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
    }

当我从图库中选择图像并将其放在屏幕上的imageView中时,我的网络服务正在运行。但是当我拍照时,我需要先将它保存到库中,我现在已经完成但是我遗漏的部分是如何以编程方式从库中引用这个新创建的照片。

更新 我假设从nsurl转换为nsdata将在下面的相机块中检索如下。注意当用户选择拍照选项时,cameraBool设置为true。 ImageChanged在imagePickerController函数中设置

if (imageChanged){
        //changed from placeholder
            if (!cameraBool){
                //retrieved from gallery
                let image = pic
                let imageData = UIImagePNGRepresentation(image)
            }
            else{
                //retrieved from camera
                let imageData = NSData(contentsOfURL: cameraPath)
            }
        }
        else{
            //upload nil
            let imageData = nil
        }

我的问题是图像的路径只在我的imagePickerController函数中定义。所以我需要在文件顶部声明cameraPath,以便它可以在imagePickerController函数中使用,然后在我的上传webservice中使用。我似乎无法将cameraPath初始化为nil。所以我不确定如何初始化它?

var cameraPath : NSURL = nil
//not allowed

当我刚才:

var cameraPath : NSURL

我收到的错误是我的控制器没有初始化程序

3 个答案:

答案 0 :(得分:4)

您可以通过相机以这种方式获取最近添加的图像的路径:

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
    imagePicked.image = image
   if (cameraBool){
        var imageData = UIImageJPEGRepresentation(imagePicked.image, 0.6)
        var compressedJPGImage = UIImage(data: imageData)
        ALAssetsLibrary().writeImageToSavedPhotosAlbum(compressedJPGImage!.CGImage, orientation: ALAssetOrientation(rawValue: compressedJPGImage!.imageOrientation.rawValue)!,
        completionBlock:{ (path:NSURL!, error:NSError!) -> Void in
            println("\(path)")  //Here you will get your path
        })
    }
    self.dismissViewControllerAnimated(true, completion: nil);
}

将打印这样的路径:

assets-library://asset/asset.JPG?id=C5E0EB97-5D3D-41F9-8782-F48140144432&ext=JPG

答案 1 :(得分:1)

使用ALAssetsLibrary,如果使用UIImageWriteToSavedPhotosAlbum保存图像,则不会获得指向它的指针。更多info

编辑: 我认为@DharmeshKheni的解决方案应该有效。我的猜测是你在设置之前读取了cameraPath。换句话说:我认为你在保存之前尝试使用新图片。你能说出cameraPath的设置位置和阅读位置吗?

答案 2 :(得分:0)

您可以使用协议/委托模式。请参阅Apple Doc

基本上,您在类中使用requiered函数创建一个Protocol,设置一个委托变量,然后将Image移交给新的View Controller。您可以找到教程here