ios - 为 POST 请求使用辅助函数

标签 ios swift post helpers

我尝试为我的 POST 请求创建一个帮助程序类,并希望返回响应。然而,由于post请求是异步的,这让我感到有点困惑。

我尝试返回 NSString,但是它没有让我返回 responseresponseString。它只是让我输入 return "A"。我尝试使用 -> NSURLResponse 但也无法正常工作。

制作这样的辅助方法的正确方法是什么? (如果我得到响应后进行检查,根据响应返回true或false也可以)

class func hello(name: String) -> NSString {

    let request = NSMutableURLRequest(URL: NSURL(string: "http://www.thisismylink.com/postName.php")!)
    request.HTTPMethod = "POST"
    let postString = "Hi, \(name)"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil && data != nil else {                                                          // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")

        }

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")
    }
    task.resume()
    return "A"
}

最佳答案

由于 dataTaskWithRequest 是异步的,该函数将在执行完成 block 之前命中您的 return 语句。你应该做的是为你自己的辅助方法设置一个完成 block ,或者将某种委托(delegate)对象传递给函数,这样你就可以调用它的方法,让它知道 web 服务回调的结果是什么。

这是一个使用完成 block 的例子:

class func hello(name: String, completion: (String? -> Void)){

    let request = NSMutableURLRequest(URL: NSURL(string: "http://www.thisismylink.com/postName.php")!)
    request.HTTPMethod = "POST"
    let postString = "Hi, \(name)"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil && data != nil else {                                                          // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")

        }

        let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")

        completion(responseString);
    }
    task.resume()
}

然后使用它

<#YourClass#>.hello("name") { responseString in

    //do something with responseString
}

还没有测试代码,但应该是正确的

关于ios - 为 POST 请求使用辅助函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36075576/

相关文章:

objective-c - 在自定义纬度/经度处创建新的 CLLocationCoordinate2D

ios - 如何在 ios 6 中编写 SLComposeViewController 之前检查用户是否在 iphone 设置中输入了他的 facebook 详细信息

ios - iOS App 的私有(private)用户集

swift - 使用 NSTimer 的重复函数失败,目标为 : self in Swift

swift - 在 Swift 4 中使用 Decodable 和继承

java - 从 Curl POST 请求中提取数据

ios - 确定 UIView 何时完成布局

arrays - swift 错误 "Cannot subscript a value of type [Uint8]"

java - 在 POST 网络服务中作为表单数据访问的 URL 数据

php - Symfony2.8。如何从post请求中获取数据