0

我试图理解“枚举”以从 PHAsset 获取图像。这是一本书的示例代码(任何人都可以使用)。我添加了 println 来显示我虽然它会显示为循环的行,但令我惊讶的是它在最后返回结果。质疑为什么第 2 行是此代码的结果,而不是 1、2、3、4。如果有人可以解释,将不胜感激。

枚举ObjectsUsingBlock 结果

这里是源代码:

//
//  ViewController.swift
//  Searching for and Retrieving Images and Videos
//
//  Created by Vandad Nahavandipoor on 7/10/14.
//  Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
//  These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
//  If you use these solutions in your apps, you can give attribution to
//  Vandad Nahavandipoor for his work. Feel free to visit my blog
//  at http://vandadnp.wordpress.com for daily tips and tricks in Swift
//  and Objective-C and various other programming languages.
//
//  You can purchase "iOS 8 Swift Programming Cookbook" from
//  the following URL:
//  http://shop.oreilly.com/product/0636920034254.do
//  If you have any questions, you can contact me directly
//  at vandad.np@gmail.com
//  Similarly, if you find an error in these sample codes, simply
//  report them to O'Reilly at the following URL:
//  http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254

import UIKit
import Photos

class ViewController: UIViewController {

/* Just a little method to help us display alert dialogs to the user */
/* But once it's get ok from the device, the message will never shown up again !*/

func displayAlertWithTitle(title: String, message: String){
    let controller = UIAlertController(title: title,
        message: message,
        preferredStyle: .Alert)

    controller.addAction(UIAlertAction(title: "OK",
        style: .Default,
        handler: nil))

    presentViewController(controller, animated: true, completion: nil)

}

override func viewDidAppear(animated: Bool) {

    super.viewDidAppear(animated)

    PHPhotoLibrary.requestAuthorization{
        [weak self](status: PHAuthorizationStatus) in

        dispatch_async(dispatch_get_main_queue(), {

            switch status{
            case .Authorized:
                self!.retrieveImage()
            default:
                self!.displayAlertWithTitle("Access",
                    message: "I could not access the photo library")
            }
        })

    }

}

func retrieveImage() {
    super.viewDidLoad()

    /* Retrieve the items in order of modification date, ascending */
    let options = PHFetchOptions()
    options.sortDescriptors = [NSSortDescriptor(key: "modificationDate",
        ascending: true)]

    /* Then get an object of type PHFetchResult that will contain
    all our image assets */
    let assetResults = PHAsset.fetchAssetsWithMediaType(.Image,
        options: options)

    if assetResults == nil{
        println("Found no results")
        return
    } else {
        println("Found \(assetResults.count) results")
    }

    let imageManager = PHCachingImageManager()

    assetResults.enumerateObjectsUsingBlock{(object: AnyObject!,
        count: Int,
        stop: UnsafeMutablePointer<ObjCBool>) in

        if object is PHAsset{How
            let asset = object as PHAsset
            println("Inside  If object is PHAsset, This is number 1")

            let imageSize = CGSize(width: asset.pixelWidth,
                height: asset.pixelHeight)

            /* For faster performance, and maybe degraded image */
            let options = PHImageRequestOptions()
            options.deliveryMode = .FastFormat

            imageManager.requestImageForAsset(asset,
                targetSize: imageSize,
                contentMode: .AspectFill,
                options: options,
                resultHandler: {(image: UIImage!,
                    info: [NSObject : AnyObject]!) in

                    /* The image is now available to us */

                    println("enum for image, This is number 2")


            })

            println("Inside  If object is PHAsset, This is number 3")
        }
        println("Outside If object is PHAsset, This is number 4")

    }

  }

}
4

1 回答 1

1

因为requestImageForAsset默认异步执行,并且resultHandler在主线程上排队。在您的枚举完成之前,不会执行这些排队的结果处理程序。

于 2014-11-30T05:42:01.487 回答