【问题标题】:.enumerateGroupsWithTypes block stop parameter Swift (Xcode 6 beta 5).enumerateGroupsWithTypes 块停止参数 Swift (Xcode 6 beta 5)
【发布时间】:2017-08-20 09:32:33
【问题描述】:

今天我将 Xcode 6 升级到了 beta 5(从 beta 1),正如你想象的那样,我发现我以前完美运行的 Swift 应用程序充满了各种错误(嗯,与 beta 1 相比发生了很大变化)。在所有错误中,有一个我只是不知道如何修复。它与快速闭包有关,特别是 .enumerateGroupsWithTypes 方法的 enumerationBlock 参数。代码如下:

assetLib.enumerateGroupsWithTypes(ALAssetsGroupType(ALAssetsGroupSavedPhotos), usingBlock: {
(group: ALAssetsGroup?, stop: CMutablePointer<ObjCBool>) in

...

}, failureBlock: {
  (error: NSError!) in

  ...

})

这确实在 Swift(Xcode 6 beta 1)中完美运行。但现在,我得到 2 个错误:

  1. “‘UnsafeMutablePointer’不是‘错误类型’的子类型”

  2. "使用未声明的类型'CMutablePointer'"

很明显 CMutablePointer 已经不存在了,所以我尝试修改 stop 参数:

..., stop: UnsafeMutablePointer<ObjCBool> ...

这个改动之后,第二个错误明显消失了,但是第一个变成了:

" 找不到接受提供的参数的 'init' 的重载"

我什至尝试按照this post 的建议将 UnsafeMutablePointer 更改为 UnsafePointer。

编辑:

这里是 enumerateGroupsWithTypes 方法的完整代码:

assetLib.enumerateGroupsWithTypes(ALAssetsGroupType(ALAssetsGroupSavedPhotos), usingBlock: {
    (group: ALAssetsGroup?, stop: UnsafeMutablePointer<ObjCBool>) in
    if group != nil {
    group!.setAssetsFilter(ALAssetsFilter.allPhotos())
    group!.enumerateAssetsAtIndexes(NSIndexSet(index: group!.numberOfAssets()-1), options: nil, usingBlock: {
      (result: ALAsset!, index: Int, stop: UnsafeMutablePointer<ObjCBool>) in
      if result {
        var alAssetRapresentation: ALAssetRepresentation = result.defaultRepresentation()
        url = alAssetRapresentation.url()
      }
      })
    }
    else if group == nil {

      assetLib.assetForURL(url, resultBlock: {
        (asset: ALAsset!) in
        if asset != nil {
        var assetRep: ALAssetRepresentation = asset.defaultRepresentation()
        var iref = assetRep.fullResolutionImage().takeUnretainedValue()
        var image = UIImage(CGImage: iref)


        imageView.image = image

        self.view.addSubview(imageView)

          let mask = CAShapeLayer()
          mask.path = UIBezierPath(ovalInRect: CGRectMake(0, 0, 200, 200)).CGPath
          mask.frame = CGPathGetPathBoundingBox(mask.path)

          mapView.layer.mask = mask

          self.view.addSubview(mapView)

        }
        }, failureBlock: {
          (error: NSError!) in

          NSLog("Error!", nil)
        })
    }

    }, failureBlock: {
      (error: NSError!) in

      NSLog("Error!", nil)

    })

【问题讨论】:

  • stop: CMutablePointer&lt;ObjCBool&gt; 替换为stop: UnsafeMutablePointer&lt;ObjCBool&gt; 后,您的代码将在我的项目中编译。是否还有更多可能导致问题的代码?
  • 首先,感谢您的快速回复...块内有很多东西。如果您的代码编译,我的代码中的错误可能隐藏在其他地方。我会在几分钟后发布完整方法的更新!
  • 也许您可以将“很多东西”简化为一个展示问题的最小示例:)
  • 问题是我不知道在这个“很多东西”中问题可能出在哪里......我对 ALAsset 的东西真的很陌生,我也不太熟悉闭包。我需要一些帮助:P
  • NSLog("Error!", nil) 错误,应该是NSLog("Error!")

标签: ios xcode swift


【解决方案1】:

这是一个适合我的工作示例:此代码查找专辑“projectname”并保护该专辑“in”中的图像。如果相册不存在,则会创建相册。

注意:如果有同名专辑。您不能再次使用此名称创建相册。您必须使用新名称。在此示例中,项目名称将扩展为日期和时间。

顺便说一句,Apple 的应用程序可以创建同名专辑。

    func saveImage(projectName : String) { // Return a new projectname  
                                      //  in the var self.newProjectName if the old one could not created
    if self.isSaved {  // was here bevor
        return
    }

    let library = ALAssetsLibrary()                 // This object will provide the access to to the library

    // List over all groups in the PhotoDirectory
    // ALAssetsGroupAll is the key to select the listed groups
    // possible change to type:Album
    library.enumerateGroupsWithTypes(ALAssetsGroupType(ALAssetsGroupAll),
        usingBlock: {(group : ALAssetsGroup!, stop : UnsafeMutablePointer<ObjCBool>) in
            if group != nil {                                   // The listing of the directory content has found an object
                // Did we search for this album?
                if group.valueForProperty(ALAssetsGroupPropertyName).isEqualToString(projectName) {
                    stop.initialize(true)                       // Stop the enumeration thread
                    library.writeImageToSavedPhotosAlbum(self.cgImage, metadata: self.ciImage?.properties(),
                        completionBlock: {(assetUrl, error: NSError?) -> Void in
                        if let theError = error?.code {
                            lapApp.logger.addLog("saved image failed, first try \(error?.localizedDescription) code \(theError)")
                        } else {
                            library.assetForURL(assetUrl,
                                resultBlock: { (asset: ALAsset!) -> Void in
                                group.addAsset(asset)
                                self.isSaved = true
                                return // Stop this process and leave
                                }, failureBlock: {
                                    (theError: NSError!) -> Void in
                                    lapApp.logger.addLog("error occurred, image to album at the first try: \(theError.localizedDescription) ")
                            })
                        }
                    })
                    return // write image to the found album
                } else {
                 // Album not found, enumeration will continue
               }
            }
            else { // The album was not found, so we will create an album
                if stop.memory.boolValue {  // The enumeration will go over the end of the list. The stop-signal comes some time to late?
                    return
                }
                library.addAssetsGroupAlbumWithName(projectName,
                    resultBlock: {(group: ALAssetsGroup?) -> Void in
                    if let thegroup = group {         // Check for a name conflict, possible was a album with the same name deleted. IOS8 will not create this album!
                        // The album was correct created, now we will add the picture to the album
                        library.writeImageToSavedPhotosAlbum(self.cgImage, metadata: self.ciImage?.properties(), completionBlock: {
                            (assetUrl, error: NSError?) -> Void in
                            if let theError = error?.code {
                                lapApp.logger.addLog("save image in new album failed. \(error?.localizedDescription) code \(theError)")
                            } else {
                                library.assetForURL(assetUrl,
                                    resultBlock: { (asset: ALAsset!) -> Void in
                                    thegroup.addAsset(asset)
                                    self.isSaved = true
                                    stop.initialize(true)                       // Stop the enumeration thread
                                    return
                                    }, failureBlock: {
                                        (theError: NSError?) -> Void in
                                        lapApp.logger.addLog("error occurred: \(theError?.localizedDescription)")
                                })
                            }
                        })
                        return

                    } else {                       // Name conflic with a deleted album.
                                                   // Work around: Create the Album with the Projectname an extend the name with Date and time
                        let formatter : NSDateFormatter = NSDateFormatter()
                        formatter.dateFormat = "yy.MM.dd hh:mm:ss"
                        let extensionDate = formatter.stringFromDate(NSDate())
                        self.newProjectName = projectName + " " + extensionDate // This is the new projectname
                        library.addAssetsGroupAlbumWithName(self.newProjectName,
                            resultBlock: {(group: ALAssetsGroup?) -> Void in
                            if let theGroup = group {
                                library.writeImageToSavedPhotosAlbum(self.cgImage, metadata: self.ciImage?.properties(), completionBlock: {
                                    (assetUrl, error: NSError?) -> Void in
                                    if let theError = error {
                                       lapApp.logger.addLog("save image with new album name failed. \(error?.localizedDescription) code \(theError) \(self.newProjectName)")
                                    } else {
                                       library.assetForURL(assetUrl, resultBlock: { (asset: ALAsset!) -> Void in
                                        theGroup.addAsset(asset)
                                        self.isSaved = true
                                        stop.initialize(true)                       // Stop the enumeration thread
                                        return
                                        }, failureBlock: {
                                            (theError: NSError?) -> Void in
                                            lapApp.logger.addLog("error at write image in new album occurred: \(theError?.localizedDescription)")
                                        })
                                    }
                                })
                            } else {
                                lapApp.logger.addLog("Problem adding albums with the name \(self.newProjectName)")
                            }
                        },
                        failureBlock: {
                                (error:NSError?) -> Void in
                                lapApp.logger.addLog("Problem adding albums: \(error)")
                        })
                    }
                    },
                    failureBlock: {
                        (error:NSError?) -> Void in
                        lapApp.logger.addLog("Problem loading albums: \(error)")
                })
            }
        }, failureBlock: { (error:NSError?) in lapApp.logger.addLog("Problem loading albums: \(error)") })
} // End SaveImage

【讨论】:

    【解决方案2】:

    NSLog("Error!", nil) 错误,应该是NSLog("Error!")。 (这似乎会混淆 Swift 编译器并导致不相关的错误消息。)

    【讨论】:

      猜你喜欢
      • 2014-10-15
      • 1970-01-01
      • 2014-09-28
      • 1970-01-01
      • 1970-01-01
      • 2014-10-29
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      相关资源
      最近更新 更多