Appframe Knowledge Base

1 hits

REST API resource call from Swift

The SendRequestToRest function below takes the following paramets: RequestURL - Example: Username Password The function will return a NSDictionary, containing either the result from the resource call, or an error message. func SendRequestToREST(RequestURL : String, Username : String, Password : String, DataLoadedHandler: (RESTResult: NSDictionary) -> Void){ //REST API requires user credentials to be base64 encoded let UserLoginBase64 = Base64EncodeUserString(Username, Password: Password) let url = NSURL(string: RequestURL) //Create request, and add REST API request headers. let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "GET" request.addValue("Basic " + UserLoginBase64, forHTTPHeaderField: "Authorization") request.addValue("application/json", forHTTPHeaderField: "Accept") //Send asynchronous request with our URL and request headers. let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error -> Void in if error == nil{ //Parse json response let resultDictionary: NSDictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary DataLoadedHandler(RESTResult: resultDictionary) }else{ let ErrorMessage: NSDictionary = ["Connection Error":"Could not connect to service, please verify that your connection string is correct."] DataLoadedHandler(RESTResult: ErrorMessage) } }) task.resume() } //Function that is utilized to encode the user credentials in the request header. private func Base64EncodeUserString(Username : String, Password: String) -> String { let UserLoginString = Username + ":" + Password let UserLoginPlainData = (UserLoginString as NSString).dataUsingEncoding(NSUTF8StringEncoding) return UserLoginPlainData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) }

rest api · Perma link post comment Posted by: Steffen Opheim (17-aug-2015)