Alan Tingey
Alan Tingey

Reputation: 971

iOS Swift 3 POST issue

I had some code that I used a while back that worked perfectly. I now wish to use it in my new project which is swift 3 and although I have fixed most errors I still have two left as follows:

The following line of code: var _: NSData? = NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response) as NSData produces the following error: Call can throw, but it is not marked with 'try' and the error is not handled

The following line of code: NSLog("Response code: %ld", res?.statusCode ?? <#default value#>); Produces the following error: Editor placeholder in source file.

Any help is appreciated.

Below is the full code which may help solve the issue:

        func webViewDidFinishLoad(_ webView: UIWebView) {
        UIApplication.shared.isNetworkActivityIndicatorVisible = false

        let post:NSString = "userid=349&devicetoken=walan"

        NSLog("PostData: %@",post);

        let url:NSURL = NSURL(string: "https://str8red.com/updateAPN")!

        let postData:NSData = post.data(using: String.Encoding.ascii.rawValue)! as NSData

        let postLength:NSString = String( postData.length ) as NSString

        let request:NSMutableURLRequest = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"
        request.httpBody = postData as Data
        request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")


        var _: NSError?
        var response: URLResponse?

        var _: NSData? = NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response) as NSData


        let res = response as! HTTPURLResponse!;

        NSLog("Response code: %ld", res?.statusCode ?? <#default value#>);

}

Upvotes: 0

Views: 103

Answers (1)

Wismin
Wismin

Reputation: 1145

You could add try keyword and surround the statement with do {} catch {} as follows:

do {

 try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response) as NSData
} catch {
    print(error)
}

You will still have a warning about the function has been deprecated since iOS 9.

I will see try to see how the whole function could be re-write in iOS 10, Swift 3.1 syntax, but there's a danger that it might break and will look very different from the rest of your legacy code. Stay tuned, I will update this answer again.

As for the 'placeholder error' you could put some value like '500' for example to default to 'Internal server error'

NSLog("Response code: %ld", res?.statusCode ?? 500); 

Update: Here is the function updated to Swift 3, iOS 10.

I only update based on the original intent of the function. Just syntax / API update, no removal / adding any functionality.

func webViewDidFinishLoad(_ webView: UIWebView) {
    UIApplication.shared.isNetworkActivityIndicatorVisible = false

    let post:String = "userid=349&devicetoken=walan"

    NSLog("PostData: %@",post);

    let url:URL = URL(string: "https://str8red.com/updateAPN")!

    let postData:Data = post.data(using: String.Encoding(rawValue: String.Encoding.ascii.rawValue))!

    let postLength: String = String( postData.count )

    var request:URLRequest = URLRequest(url: url as URL)

    request.httpMethod = "POST"
    request.httpBody = postData as Data
    request.setValue(postLength, forHTTPHeaderField: "Content-Length")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")

    var _: NSError?
    var response: URLResponse?

    URLSession.shared.dataTask(with: request) { (data, res, error) in

        guard error == nil  else {
            print(error!)
            return
        }

        response = res
    }

    let res = response as! HTTPURLResponse!;

    NSLog("Response code: %ld", res?.statusCode ?? 500);   
}

Upvotes: 1

Related Questions