带有返回字符串的iOS swift post方法

标签 ios swift post

如何使用返回获取的字符串编写post方法

func post(link:String,passedPostString:String) {
    let request = NSMutableURLRequest(url: NSURL(string: link)! as URL)
    request.httpMethod = "POST"


    request.httpBody = passedPostString.data(using: String.Encoding.utf8)

    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in

        if error != nil {
            print("error=\(String(describing: error))")
            print("******Error*****")
            return

        }
        let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

      print(responseString!)




    }
    task.resume()
}

然后我把它叫做类似的东西

var link  = "link"
var passedPostString = "passedPostString"
print(post(link: link , passedPostString: passedPostString ))

返回获取的值

最佳答案

dataTask 方法是异步的,因此无法立即返回值,因为您不知道何时调用它。

最好的办法是传入一个完成处理程序,它将从您的主代码中异步调用:

func post(link:String, passedPostString:String, completionHandler: @escaping (NSString) -> ()) {
    let request = NSMutableURLRequest(url: NSURL(string: link)! as URL)
    request.httpMethod = "POST"


    request.httpBody = passedPostString.data(using: String.Encoding.utf8)

    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in

        if error != nil {
            print("error=\(String(describing: error))")
            print("******Error*****")
            return

        }
        let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

        completionHandler (responseString!);
    }
    task.resume()
}


var link  = "link"
var passedPostString = "passedPostString"
let completion = { (result: NSString) in print(result) }
post(link: link, passedPostString: passedPostString, completionHandler: completion)

关于带有返回字符串的iOS swift post方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45060905/

相关文章:

iphone - 当 didUpdateToLocation 收到消息时,我可以在后台做什么?

ios - 使用 SQLite Swift4 时出错 : multi-threaded access to database connection

ios - 为各种 iPhone 屏幕尺寸动态调整 UICollectionView 单元格宽度的宽度

ios - 让 Apple Push 恢复工作,我是否需要推送 iOS 应用程序更新?

java - 在java中将自定义RequestBody从POST请求发送到外部GET请求

ios - 我可以从 UIActivityViewController 和 native UIActivityTypePostToTwitter 发送动画 GIF 吗?

ios - 在 Popover tableview 中选择单元格后 UILabel 不刷新

ios - 建筑的 undefined symbol ..在动态框架中

php - 如何在 wordpress divi 主题帖子或页面中添加 php 代码

php - Silverstripe - 检索数组中的 POST 数组