iOS:网络操作后从函数返回值

时间:2016-04-22 20:15:05

标签: ios swift closures

我必须在MLPAutoCompleteTextField委托方法中的网络操作后返回一个数组。任何与此相关的建议都非常有帮助。

func autoCompleteTextField(textField: MLPAutoCompleteTextField!, possibleCompletionsForString string: String!, completionHandler handler: (([AnyObject]!) -> Void)!) {
    //Perform network operation. Success and Failure conditions are handled below by implementing the protocol
    service.getData(string)

    //Have to return this only after network operation is completed either success or failure
    handler(autoCompleteSuggestionsArray)
}

//Handle successful network call 
func handleSuccess(model: Model) {
    autoCompleteSuggestionsArray.removeAll()
    for item in model.items {
        if let itemName = item.name {
            autoCompleteSuggestionsArray.append(itemName)
        }
    }
}

//Handle failed network call
//
func handleErrorWithMessage(message: String) {
    autoCompleteSuggestionsArray.removeAll()
}

1 个答案:

答案 0 :(得分:0)

由于示例中显示的原因,拥有成功和失败的委托方法而不是回调闭包不是一个很好的方法:您不能在委托方法中包含autoCompleteTextField方法范围内的参数。如果您能够更改服务实现以获取闭包而不是使用委托,例如service.getData(string:String, success:SuccessClosure, failure:FailureClosure),这将是一个更好的整体情况。

如果你无法做出改变,那么你必须做一些不幸的事情,比如:

var autocompleteHandler:([AnyObject]->())? //Create a new property on your class to hold an optional reference to the handler that is visible to multiple methods

func autoCompleteTextField(textField: MLPAutoCompleteTextField!, possibleCompletionsForString string: String!, completionHandler handler: (([AnyObject]!) -> Void)!) {
    //Save reference to handler in scope that is also visible to delegate methods
    autocompleteHandler = handler

    //Perform network operation. Success and Failure conditions are handled below by implementing the protocol
    service.getData(string)
}

//Handle successful network call 
func handleSuccess(model: Model) {
    autoCompleteSuggestionsArray.removeAll()
    for item in model.items {
        if let itemName = item.name {
        autoCompleteSuggestionsArray.append(itemName)
        }
    }
    // Now that we have a result from the service, pass it to the saved handler if it is not nil
    autocompleteHandler?(autocompleteSuggestionsArray)
}

//Handle failed network call
func handleErrorWithMessage(message: String) {
    autoCompleteSuggestionsArray.removeAll()
    // Now that we have a result from the service, pass it to the saved handler if it not nil
    autocompleteHandler?(autocompleteSuggestionsArray)
}