无法在 AppDelegate 应用程序方法中加载数组中的 HTTP POST 响应数据。如何解决这个问题?

Unable to load HTTP POST response data in array in AppDelegate application method. How to solve this issue?

请在 AppDelegate.swift 中找到以下代码片段 我想要实现的是能够使用我自己的 API 收到的图像 url 填充 'images' 数组,并进一步将此图像数组迁移到视图控制器(可以使用委托完成)。 我确实在 "print(self.images[index])" 处获得了图像 URL 列表,但是“images.isEmpty”returns 是正确的。我哪里错了?

示例控制台输出:

2016-01-03 19:28:48.767 Mobblr[22372:1347546] 未知 class Interface Builder 文件中的 ContentViewContr。
此处显示的图像 URL 列表

var images = [String]()    
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    preloadData()
    print(images.isEmpty)

    var pageControl = UIPageControl.appearance()
    pageControl.pageIndicatorTintColor = UIColor.lightGrayColor()
    pageControl.currentPageIndicatorTintColor = UIColor.blackColor()
    pageControl.backgroundColor = UIColor.whiteColor()
    return true
}

func preloadData() {
    let parameters = ["count": 100]
    Alamofire.request(.POST, <My API>, parameters: parameters, encoding: .JSON)
        .responseJSON { response in
            if let value: AnyObject = response.result.value {

                let posts = JSON(value)
                //print(posts)
                for index in 0..<posts.count {
                    //print(posts[index]["image_url"])
                    if let image = posts[index]["image_url"].string {
                        self.images += [image]
                        print(self.images[index])

                    } else {
                        self.images += [""]
                    }
                }

    }

}

你说“images.isEmpty returns 正确”。 Where/when 你在检查吗?

此请求异步运行(它应该异步运行,因为您不想在检索图像 URL 时阻止您的应用程序),因此很可能想要使用 images 的视图控制器是在请求完成之前检查。所以问题是当 images 被成功检索时,你如何通知视图控制器(或等待 images 被填充的任何东西)。

您可以为此使用通知。因此,responseJSON 完成块可以 post 通知:

Alamofire.request(.POST, <My API>, parameters: parameters, encoding: .JSON)
    .responseJSON { response in
        // process the response here

        // now post notification

        NSNotificationCenter.defaultCenter().postNotificationName(imagesNotificationKey, object: nil)
}

这假设您有一些全局变量是此通知的关键:

let imagesNotificationKey = "..."

并且任何想要在收到此通知后采取某些操作的视图控制器都可以将自己添加为观察者:

class ViewController: UIViewController {

    var observer: NSObjectProtocol?

    override func viewDidLoad() {
        super.viewDidLoad()

        observer = NSNotificationCenter.defaultCenter().addObserverForName(imagesNotificationKey, object: nil, queue: NSOperationQueue.mainQueue()) { notification in
            // do something (e.g. reload table or what have you)
        }
    }

    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(observer!)
    }

}