ios - 我如何将数据传递给 swift4 中的变量?

标签 ios swift

我需要在另一个 View Controller 中使用输出数据,但我不能使用,该字符串仅返回一个空字符串:

func callApi(postString: String) -> (String) {
    var outputdata = String()
    var req = LogIn(postString: postString)
    let task = URLSession.shared.dataTask(with: req) { (data, response, error) in
        if let data = data{
            outputdata = String(data: data, encoding: String.Encoding.utf8)!
            //print(outputdata)


        }
    }

    print(outputdata)
    return (outputdata)
}

最佳答案

您可以尝试这个,因为该过程是异步的

func callApi(_ postString: String,completion:@escaping:(_ res:String?) -> Void ) {
     var req = LogIn(postString: postString)
    URLSession.shared.dataTask(with: req) { (data, response, error) in
        if let data = data{
            completion(String(data: data, encoding: String.Encoding.utf8))     
        }
        else {
            completion(nil)
        }
    }.resume()
 }

通话

callApi("SendedValue") {  res in
  print(res)
}

关于ios - 我如何将数据传递给 swift4 中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52355795/

相关文章:

ios - 由核心数据填充的表无法正确显示

ios - UICollectionView - 在横向模式下重新设计

swift - Realm Sandbox OS X 问题

Swift - 仅从字符串中获取字母

ios - CollectionView referenceSizeForHeaderInSection 是应用程序崩溃的原因

ios - 如何检测 UILabel(没有设置宽度,只是自动布局)是否被截断(你好,我是测试......)?

ios - Xcode 9.3 中 Swift 的 -Osize build设置是什么?

ios - tableView beginUpdates/endUpdates block 重新加载整个表,即使为空

iphone - 在 CTCallCenter callEventHandler 中取消隐藏 View 非常慢

ios - 在 iOS App 中检测电话号码