简体   繁体   English

如何快速接收服务器的响应?

[英]How to recieve response from server in swift?

func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
        NSLog("Received response\(response)")
        myResponseData = NSMutableData()
}

func connection(connection: NSURLConnection, didReceiveData data: NSData) {
     myResponseData.appendData(data)
}

func connectionDidFinishLoading(connection: NSURLConnection) {
     NSLog("\(myResponseData)");
     let strData = NSString(data: myResponseData, encoding: NSUTF8StringEncoding)
     print("Body: \(strData)", terminator: "")

How can we receive a response from a server and according to that set an alert message, like if the status is success we have to show an alert message 我们如何接收来自服务器的响应并根据该响应设置警报消息,例如,如果状态为成功,则我们必须显示警报消息

An easy, but not so scalable solution is: 一个简单但不那么可扩展的解决方案是:

    • create a subclass of NSURLRequest. 创建NSURLRequest的子类。 Override the initWithRequest:delegate:startImmediately: method and make this class its own delegate. 重写initWithRequest:delegate:startImmediately:方法,并使此类成为自己的委托。 Pass NO to super as last argument. 将NO传递给super作为最后一个参数。
    • Implement the delegate methods. 实现委托方法。
    • Create an NSURLRequest 创建一个NSURLRequest
    • create an instance of your subclass using the NSURLRequest you just created. 使用刚创建的NSURLRequest创建子类的实例。
    • Call -start on you connection. 在您的连接上致电-start。 Make sure your connection is a property if some class that outlives the connection, otherwise the connection will be deallocated before it has a chance to do anything. 如果某个类的寿命比连接长,请确保您的连接是一个属性,否则,将在该连接有机会执行任何操作之前将其释放。

Note that NSURConnection is deprecated in favor of NSURLSession. 请注意,不推荐使用NSURConnection,而推荐使用NSURLSession。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建可以从IOS(swift)应用程序连续接收数据的AWS服务器? - How do I create an AWS server that could recieve data continously from an IOS(swift) app? swift-如何从服务器获取JSON响应 - swift - how to get JSON response from server 如何在Swift 3中将来自服务器的响应从字符串转换为数组? - How to convert the response got from a server from string to array in swift 3? iOS Swift:如何将响应从服务器更改为特定格式? - iOS Swift: How to change the Response from server to Specific Format? 如何在Swift 3中将数据附加到来自服务器响应的字典中? - How to append the data to dictionary coming from server response in swift 3? 从IOS MKNetwork接收图像到PHP服务器 - Recieve image from IOS mknetwork to php server 从swift文件发送通知并在ios中接收目标c文件 - send notification from swift file and recieve in objective c file in ios 如何在Swift中查看来自HTTP GET请求的服务器响应? - How can I see the server response from an HTTP GET request in Swift? 我如何继续旋转图像,直到服务器迅速做出响应 - How do i keep on rotating an image until a response from a server in swift 如何在Swift中使用OCMock模拟来自AFNetworking的响应? - How to mock response from AFNetworking with OCMock in Swift?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM