0

I have a recursive function with an async request. I want to save in an array if the requests were successful, but i don't know how. Concrete it is a function to upload files and if the function get a folder than the files inside this folder should also be uploaded.

I thought about implement this with a completionHandler, something about this:

func uploadFiles(pathToFile: NSURL) ->[Bool]{
    var suc: [Bool] = [Bool]()
    self.uploadFileRec(pathToFile, suc: &suc){
        (result: [Bool]) in
        println(result)
    }
    return suc
}

func uploadFilesRec(pathToFile: NSURL, inout suc: [Bool], completionHandler: (result: [Bool]) -> Void){
    var isDir: ObjCBool = ObjCBool(true)
    var manager: NSFileManager = NSFileManager.defaultManager()
    manager.fileExistsAtPath(pathToFile.path!, isDirectory: &isDir)
    if(isDir){
        var error: NSError? = nil
        let contents = manager.contentsOfDirectoryAtPath(pathToFile.path!, error: &error) as! [String]
        for fileName in contents {
            if(fileName != ".DS_Store"){
                var pathString = pathToFile.path! + "/" + fileName
                var updatePathtoFile = NSURL(fileURLWithPath: pathString)
                self.uploadFilesRec(updatePathtoFile!, suc: &suc, completionHandler: completionHandler)
                completionHandler(result: suc)
            }
        }

    }
    else{
        asyncFileUpload(...){
            ...
            suc.append(/*successful or not*/)
        }
    }
}

But the problem is that println get call not only one time but as many as uploadFileRec get called inside. So if i would call an another function instead of println, the function would be also called many times. So i think the idea with completionHandler was wrong. How else can i realize this?

4

2 回答 2

1

好的,我回答我自己的问题。

complitionHandler 的想法确实是错误的。就像我在问题中所说的那样,调用 complitionHandler 的次数与调用递归函数的次数一样多。如果您想在我的应用程序中收集响应或喜欢某些文件的上传成功,则必须使用调度组。主要思想是添加该组中的所有请求并等待所有请求完成。

在实践中,这意味着创建组:

let group = dispatch_group_create()

在调用递归函数之前输入组,然后在每次函数调用自身时输入:

dispatch_group_enter(self.group)

请求完成后离开组,与您进入组的次数一样多:

dispatch_group_leave(self.group)

并等到所有工作完成:

dispatch_group_notify(group, dispatch_get_main_queue()) {
        //Do work here
    }
于 2015-09-16T10:54:33.870 回答
0
  1. var isDir: ObjCBool = ObjCBool(true)因此,默认情况下,您将所有文件视为目录,当manager.fileExistsAtPath失败时,您将获得深度递归,因为isDirectory标志保持为 TRUE:

    如果路径不存在,则返回时该值未定义

    来自苹果文档...

  2. var pathString = pathToFile.path! + "/" + fileName- 不确定你最终得到了正确的路径。所以,你得到递归。检查你的路径字符串

  3. manager.fileExistsAtPath结果被忽略,所以,你正在做盲目上传......

解决这些问题并继续...

于 2015-09-15T10:28:11.810 回答