简体   繁体   中英

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. Override the initWithRequest:delegate:startImmediately: method and make this class its own delegate. Pass NO to super as last argument.
    • Implement the delegate methods.
    • Create an NSURLRequest
    • create an instance of your subclass using the NSURLRequest you just created.
    • Call -start on you connection. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM