I have problem when i post the data to server, it seems doesn't work at all.. I've found the code thats the other use it for post
here is the code for post
func post(params : Dictionary<String, String>, url : String, postCompleted : (succeeded: Bool, msg: String) -> ()) {
var request = NSMutableURLRequest(URL: NSURL(string: "")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
// let postString = "Body: \(personaldata.data)"
var err: NSError?
// request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(CString: personaldata.data, encoding: NSUTF8StringEncoding)
println("Body: \(personaldata.data)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
var msg = "No message"
})
task.resume()
}
and when the button send pressed, here is the code
func tapGesture(gesture: UIGestureRecognizer) {
self.performSegueWithIdentifier("analisa", sender: self)
if let Kirim = gesture.view as? UIImageView { // if you subclass UIImageView, then change "UIImageView" to your subclass
self.post(["ID":"123", "function_name":"update_db", "personal_information_table":"\(personaldata.data)"], url: "") { (succeeded: Bool, msg: String) -> () in
}
}
}
the output when println correct already,but it doesn't appear at the website, how it could be?
I hide the website address ( it only shows line with id and weight , height on it that contains in(personaldata.data)
well my friend who working on android, have sent the data successfully :/
here is the website, and that is my friends data, not mine
is my code error or what?
here is the println
Response: <NSHTTPURLResponse: 0x7fe591554d60> { URL: } { status code: 500, headers {
"Accept-Ranges" = none;
"Cache-Control" = private;
"Content-Type" = "text/plain; charset=UTF-8";
Date = "Fri, 28 Aug 2015 09:34:02 GMT";
Server = "Google Frontend";
Vary = "Accept-Encoding";
"alt-svc" = "quic=\":443\"; p=\"1\"; ma=604800";
} }
Body: {"height": 214, "weight": 123}
Status code: 500 indicates that the error can only be resolved by fixes to the Web server software. It is not a client-side problem. It is up to the operators of the Web server site to locate and analyse the logs which should give further information about the error.
Related
I am trying to upload an image from my iOS app written in swift and tried some codes I found about it but nothing works.
Uploading throung Postman works perfect. Here a screenshot of the request in Postman:
Uploading image with Postman
As you can see the API expects a the PUT request with a JSON with only one field called "avatar" and then the image in it. Also keep in mind the form-data. In the Headers I only send the token to do the authentication.
Said this, in the Swift code I try to send as params the array with only the "avatar" key with the image encoded:
func uploadImage(url: String){
let httpMethod: String = "PUT"
var token = getTokenFromNSUserDefaults()
var imageDataJpeg = UIImageJPEGRepresentation(self.myImage, 0.9)
var base64StringJpeg = imageDataJpeg.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) // encode the image
var base64StringJpeg2 = imageDataJpeg.base64EncodedStringWithOptions(nil) // encode the image
var imageDataPng = UIImagePNGRepresentation(self.myImage)
var base64StringPng = imageDataPng.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) // encode the image
var base64StringPng2 = imageDataPng.base64EncodedStringWithOptions(nil) // encode the image
// API Request
self.request(httpMethod, token: token, params:["avatar":base64StringPng2], url: url) { (succeeded: Bool, msg: String) -> () in
var alert = UIAlertView(title: "Success!", message: msg, delegate: nil, cancelButtonTitle: "Okay.")
if(succeeded) {
println("Success")
}
else {
println("Fail")
}
// Move to the UI thread
dispatch_async(dispatch_get_main_queue(), { () -> Void in
})
}
}
//// API REQUEST ////
func request(httpMethod: String, token: String, params: Dictionary<String, AnyObject>, url : String, postCompleted : (succeeded: Bool, msg: String) -> ()) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = httpMethod
var err: NSError?
if token != ""{
request.addValue("JWT \(token)", forHTTPHeaderField: "Authorization")
}
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
////Option 1
request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Disposition")
request.addValue("multipart/form-data", forHTTPHeaderField: "Accept")
////Option 2
//request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
//request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Disposition")
//request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var msg = "No message"
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &err)
println("JSON: \(json)")
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON1: '\(jsonStr)'")
postCompleted(succeeded: false, msg: "Error")
}
else {
self.parseJson(json!)
postCompleted(succeeded: true, msg: "Works!")
return
}
})
task.resume()
}
Here's the log response from the server with always a 406 error message as follows (do not look at the "censored" url):
Response: <NSHTTPURLResponse: 0x7f967bed1450> { URL: https://***********************/ } { status code: 406, headers {
Allow = "GET, PUT, DELETE, HEAD, OPTIONS";
Connection = "keep-alive";
"Content-Type" = "application/json";
Date = "Wed, 02 Dec 2015 18:30:13 GMT";
Server = "nginx/1.4.6 (Ubuntu)";
"Transfer-Encoding" = Identity;
Vary = Accept;
"X-Frame-Options" = SAMEORIGIN;
} }
Body: Optional()
JSON: nil
The operation couldn’t be completed. (Cocoa error 3840.)
Error could not parse JSON1: 'Optional()'
Fail
Thank you very much for your help in advance!
Your "params" is not in JSON format - the curly braces for JSON dictionary are missing.
Guys I am getting a response for an api call I make. it returns the whole response and I give it to the method like.
completionHandler(response: response, error: nil)
then by doing
print(response.description)
The result is that I get headers statuscode etc.
URL:
removed
Status Code:
200
Headers:
Keep-Alive: timeout=5, max=99
Content-Length: 2423
Server: Apache/2.4.10 (Debian)
SessionID: removed
Content-Type: application/json
Date: Thu, 24 Sep 2015 12:50:14 GMT
Connection: Keep-Alive
Cache-Control: no-cache
Payload:
[{"id":148,"name":"Amsterdam","avatar":"removed","cover":"removed"}]
The part I am mostly interested in is this part
Payload:
[{"id":148,"name":"Amsterdam","avatar":"removed","cover":"removed"}]
Somehow I can't extract that array of json objects. Anyone who can help me out on how to get this?
EDIT: added the method where I receive the response and pass it through
func requestObj(url: Routes, params: Dictionary<String, String>?, completionHandler: (response: Response?, error: NSError?) -> ())
{
self.requestConfig(completionHandler: { () -> () in
if let req = NSMutableURLRequest(urlString: self.config!.api!.baseUrl! + "/v2" + url.rawValue) {
do {
req.addValue(String(self.config!.api!.token!), forHTTPHeaderField: "Token")
req.addValue(String(self.sessionID), forHTTPHeaderField: "SessionID")
let opt = HTTP(req)
opt.start { response in
if let err = response.error {
print("error: \(err.localizedDescription)")
print("opt finished with error info: \(response.description)")
completionHandler(response: nil, error: nil)
}
completionHandler(response: response, error: nil)
//print("data is: \(response.data)") access the response of the data with response.data
}
}
}
}) // request a valid config before doing anything
}
This is called with
adapter.requestObj(APIAdapter.Routes.getMunicipalities, params: nil, completionHandler: {(
response, error) in
if let response = response {
print(response.description)
}
})
For SwiftHTTP, you can get the response body with:
response.data
Have you already tried with "SwiftyJson" you could save the data in a JSON object and then access the data as a Dictionary here's how I deal with the data
import Alamofire
import SwiftyJSON
func RequestImages()
{
Alamofire.request(.GET, "https://api.500px.com/v1/photos",parameters:["consumer_key":"gRU4LletUCA9RiOQhaJBAt62UyRRYUE6vsIcC7fO"])
.responseJSON { _,_,result in
switch result {
case .Success(let data):
let json = JSON(data)
debugPrint(data)
self.Photos = self.ParseJSON(json)
self.performSegueWithIdentifier("ToCollection", sender: self)
case .Failure(_, let error):
print("Request failed with error: \(error)")
}
}
}
here is some code where I use a library called Alamofire where i retrieve a response in JSON, then if data has be found i save the data in a JSON object provided by the SwiftyJSON library
let json = JSON(data)
then I have a collection of an "Image" mode called "Photos" i fill this collection by parsing the JSON data as the following
func ParseJSON(json:JSON)->[Image]
{
//Get Image_URL
var pictures = [Image]()
for result in json["photos"].arrayValue
{
pictures.append(Image(url: result["image_url"].stringValue, name: result["name"].stringValue, news: result["description"].stringValue))
}
debugPrint(pictures)
return pictures
}
I hope my implementation helps you Greetings!
Try this :-
override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url("http://yourURL")
}
func get_data_from_url(url:String) {
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
Id = label1.text //your request parameters
JId = label2.text //your request parameters
var post:NSString = "uid=\(Id)&jid=\(JId)"
//NSLog("PostData: %#",post);
var url:NSURL = NSURL(string: url)!
var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
var postLength:NSString = String( postData.length )
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("*/*", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
if urlData != nil && reponseError == nil {
let res = response as! NSHTTPURLResponse!;
//NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300) {
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %#", responseData)
if Id != nil {
extract_json(urlData!)
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failure"
if let error = reponseError {
alertView.message = (error.localizedDescription)
}
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
func extract_json(data:NSData) {
var error: NSError?
let jsonData:NSArray = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as! NSArray
let Id_temp: AnyObject? = ((jsonData)[0] as! NSDictionary)["id"]
let Name_temp: AnyObject? = ((jsonData)[0] as! NSDictionary)["name"]
}
First go to this site and validate your URL
https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo?utm_source=chrome-app-launcher-info-dialog ( GOOGLE extenstion )
then replace below given values according to your settings :-
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("*/*", forHTTPHeaderField: "Accept")
Try with this:
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:response options:0 error:&error];
Then you can do [jsonDictionary objectForKey:#""] to retrieve values.
This is Objective C, but I am sure it must be similar in Swift.
This question already has answers here:
Cocoa Error 3840 when POST Request with AFNetworking 2
(4 answers)
Closed 7 years ago.
I'm running into a service error as I try to POST some data to a server. I'm confident the error has something to do with my request structure. I'm using AFNetworking and my request looks as follows:
lazy var networkManager: AFHTTPRequestOperationManager = {
var networkManager : AFHTTPRequestOperationManager = AFHTTPRequestOperationManager()
networkManager.requestSerializer.setValue("application/json",
forHTTPHeaderField: "Content-Type")
networkManager.responseSerializer.acceptableContentTypes =
NSSet(array: ["text/plain", "text/html", "application/json"]) as Set<NSObject>
return networkManager
}()
func createNewAccount(username:String, password:String, onCompletion:Closures.ServiceResponse) -> Void{
let parameters: [String: AnyObject] = [
"newUser": [
"name": username,
"password": password
]
]
var err : NSError?
var jsonData = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err)
var jsonString = NSString(data: jsonData!, encoding: NSUTF8StringEncoding)
networkManager.POST(Constants.STAGING_URL + "/Services/UserService/UserService.svc/NewUserSignup",
parameters: jsonString,
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
println(responseObject)
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
println(error.localizedDescription)
println(operation.responseString)
})
}
I've tried variations on the parameters option and I still run into the same problem.
Now here is the method I have written by hand that works just fine and sends data to the server as expected:
func signupNewUser(userName : String, password : String){
let jsonObject: [String: AnyObject] = [
"newUser": [
"name": userName,
"password": password
]
]
var urlString = Constants.STAGING_URL + "/Services/UserService/UserService.svc/NewUserSignup"
var request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(jsonObject, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var jsonData = NSJSONSerialization.dataWithJSONObject(jsonObject, options: nil, error: &err)
var jsonString = NSString(data: jsonData!, encoding: NSUTF8StringEncoding)
request.setValue(jsonString! as String, forHTTPHeaderField: "json")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println(response)
})
task.resume()
}
The above request works just fine and the server can process the incoming JSON and save it in the database successfully.
My server is a WCF service. The interface for the method I'm calling looks like this:
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/NewUserSignup")]
Response AddNewUser(User newUser);
The actual NSError is:
Printing description of error:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x7f98a0c58910 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set., NSUnderlyingError=0x7f98a0c582f0 "Request failed: bad request (400)"}
I assume the server is fine and it just has to do with configuring the request properly with AFNetworking. Any help configuring the request properly would be appreciated.
Solution in my case was simple and had to do with the configuration of the NetworkManager.
This worked for me as the NetWorkManager will be receiving JSON from the server:
lazy var networkManager: AFHTTPRequestOperationManager = {
var networkManager : AFHTTPRequestOperationManager = AFHTTPRequestOperationManager()
var jsonRequestSerializer = AFJSONRequestSerializer()
networkManager.requestSerializer = jsonRequestSerializer
return networkManager
}()
I'm implementing the Uber's Request Endpoint in my iOS (Swift) App. The Request API/Endpoint requires the user authentication with the app, here is the doc.
For this I'm using this Oauth2.0 library
What I did is
successfully integrated the Library in my project (xCode) with the help of given installation instructions.
In My AppDelegate
let uber_OAuth_Settings = [
"client_id": "XXXXXXX9vtKzobvXXXXXX",
"client_secret": "EXXXXXXXXyFUNCa_Wez6AXXXXXXXnrXtxus",
"authorize_uri": "https://login.uber.com/oauth/authorize",
"token_uri": "https://login.uber.com/oauth/token",
"redirect_uris": ["jamesappv2://oauth/callback"], // don't forget to register this scheme
] as OAuth2JSON
var oauth:OAuth2CodeGrant!
in my method didFinishLaunchingWithOptions of Appdelegate
oauth = OAuth2CodeGrant(settings: uber_OAuth_Settings)
oauth.viewTitle = "Uber Login Service" // optional
oauth.verbose = true // For Logs
Don't forget to register url scheme i.e ("redirect_uris": ["jamesappv2://oauth/callback"])
goto your app's Target -> info Tab -> Url Types -> Click (+), image attached
In AppDelegate add method given Below and Handle the Callback Url
func application(application: UIApplication,
openURL url: NSURL,
sourceApplication: String?,
annotation: AnyObject?) -> Bool {
// you should probably first check if this is your URL being opened
var splitUrl = url.absoluteString!.componentsSeparatedByString(":")
if splitUrl[0] == ("jamesappv2") {
oauth.handleRedirectURL(url)
}
return true
}
Now in my viewController I did like this on myBtnClick
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let url = appDelegate.oauth.authorizeURL()
UIApplication.sharedApplication().openURL(url)
appDelegate.oauth.onAuthorize = { parameters in
println("Did authorize with parameters: \(parameters)")
self.navigationController?.pushViewController(self.PersonalDriverUber_VC, animated: true)
//On Authorization Goto another ViewController using pushViewController of navigationcontroller Method
}
appDelegate.oauth.onFailure = { error in // `error` is nil on cancel
if nil != error {
println("Authorization went wrong: \(error!.localizedDescription)")
}
}
Here is my debug log, I'm getting the valid response:
OAuth2: Handling redirect URL jamesappv2://oauth/callback?state=4B0EB812&code=0sXXXXXXTX7yEbS1XXXXXHuw
OAuth2: Successfully validated redirect URL
OAuth2: Authorizing against https://login.uber.com/oauth/token?state=38158941&grant_type=authorization_code&code=0sXXXXXXXX1jxTrdFQT9Huw&client_secret=EIXXXXXXXNCa_Wez6XXXXXw0BlnrXtxus&client_id=fXXXXXXXy2LOUo9vtKXXXXXQ1nUDO&redirect_uri=jamesappv2%3A%2F%2Foauth%2Fcallback
OAuth2: Exchanging code 0swNXXXXX7yXXXXXXdFQT9Huw with redirect jamesappv2://oauth/callback for token at Optional("https://login.uber.com/oauth/token")
OAuth2: Did receive access token: Dfq3XXXXXXuWgpaqFXXXXXXXgXW, refresh token: EmStT7FEXHRMlS8odPzs1nsha0ObjK
Did authorize with parameters: [token_type: Bearer, expires_in: 2592000, access_token: XXXXXXOZuWgXXXXXXXXuJYOmgXW, refresh_token: EXXXXXHRMlS8oXXXXXXXa0ObjK, scope: profile, last_authenticated: 1430121470]
Notice I'm getting the valid access_token
Here I'm stuck
As per DOCs says in STEP4 *USE BEARER TOKEN
Pass the access_token returned in the response in the Authorization header with the type Bearer to make requests on behalf of a user.*
curl -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' 'https://api.uber.com/v1/products?latitude=37.7759792&longitude=-122.41823'
I am not getting the point. How should I pass the access_token in Header with type Bearer? I have done like below
func callRequestAPI(url:String){
let request = appDelegate.oauth.request(forURL: NSURL(string:url)!)
request.HTTPMethod = "POST"
let postString = "product_id="+selectedUberProductId+"&start_latitude="+start_lat+"&start_longitude="+start_lng+"&end_latitude="+end_lat+"&end_longitude="+end_lng
println(postString)
let tempData: NSData = appDelegate.oauth.accessToken.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = tempData.base64EncodedStringWithOptions(nil)
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("Bearer \(base64LoginString)", forHTTPHeaderField: "Authorization")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { data, response, error in
if error != nil {
println("error=\(error)")
return
}
println("response = \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
}
task.resume()
}
but I'm getting following response
response = <NSHTTPURLResponse: 0x1a284b50> { URL: https://sandbox-api.uber.com/v1/requests } { status code: 401, headers {
"Content-Length" = 75;
"Content-Type" = "application/json";
Date = "Mon, 27 Apr 2015 10:22:01 GMT";
Server = nginx;
"Strict-Transport-Security" = "max-age=31536000; includeSubDomains; preload";
"x-uber-app" = "uberex-sandbox";
"x-xss-protection" = "1; mode=block";
} }
responseString = Optional({"message":"Invalid OAuth 2.0 credentials provided.","code":"unauthorized"})
Finally I have done it :)
I changed the method like below and it Worked
func callRequestAPI(url:String){
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration)
let params:[String: AnyObject] = [
"product_id" : selectedUberProductId,
"start_latitude" : start_lat,
"start_longitude" : start_lng,
"end_latitude" : end_lat,
"end_longitude" : end_lng]
let request = appDelegate.oauth.request(forURL: NSURL(string:url)!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err)
let task = session.dataTaskWithRequest(request) {
data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 202 {
println("response was not 202: \(response)")
return
}
}
if (error != nil) {
println("error submitting request: \(error)")
return
}
// handle the data of the successful response here
var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as! NSDictionary
println(result)
if let request_id: String = result["request_id"] as? String{
println(request_id)
}
if let driver: String = result["driver"] as? String{
println(driver)
}
if let eta: Int = result["eta"] as? Int{
println(eta)
}
if let location: String = result["location"] as? String{
println(location)
}
if let status: String = result["status"] as? String{
println(status)
}
if let surge_multiplier: Int = result["surge_multiplier"] as? Int{
println(surge_multiplier)
}
if let vehicle: String = result["vehicle"] as? String{
println(vehicle)
}
}
task.resume()
}
here is the Response I Got, Parsing is also given in my above method
{
driver = "<null>";
eta = 15;
location = "<null>";
"request_id" = "ea39493d-b718-429f-8710-00a34dcdaa93";
status = processing;
"surge_multiplier" = 1;
vehicle = "<null>";
}
Enjoy
Updated for Swift 2. I used the same setup and library for oauth that Qadir describes in his question. I updated his request to work in Swift 2. Hope this helps others.
uberRequest:
let params:[String:AnyObject] = [
"product_id" : uberProduct,
"start_latitude" : userLat,
"start_longitude" : userLng,
"end_latitude" : barLat,
"end_longitude" : barLng]
let urlPath = "https://sandbox-api.uber.com/v1/requests"
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration)
guard let endpoint = NSURL(string: urlPath) else { print("Error creating endpoint");return }
let request = appDelegate.oauth.request(forURL: NSURL(string:urlPath)!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField:"Content-Type")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted)
request.HTTPMethod = "POST"
print("Prepare to make request -> \(request)")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if error != nil{
print("Error -> \(error)")
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
print("Result -> \(result)")
} catch {
print("Error -> \(error)")
}
}
task.resume()
It returns:
Result -> Optional(["driver": <null>, "request_id": 5834384c-7283-4fe6-88a7-e74150c6ab30, "surge_multiplier": 1, "location": <null>, "vehicle": <null>, "status": processing, "eta": <null>])
To use the token just follow step 5 of the instructions in the OAuth2 library, like you did before you started to try to sign it yourself a second time. The request has already been signed and has the Bearer token set up, there is nothing left to do for you:
let url = NSURL(string: "https://api.uber.com/v1/products?latitude=37.7759792&longitude=-122.41823")
let req = appDelegate.oauth.request(forURL: url)
// customize your request, if needed. E.g. for POST:
req.HTTPMethod = "POST"
// send the request
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(req) { data, response, error in
if nil != error {
// something went wrong
}
else {
// check the response and the data
// you have just received data with an OAuth2-signed request!
}
}
task.resume()
So Im in the early stages of learning swift, and I'm trying to make a trivial class to wrap the process of sending/retrieving data from a given web service. The issue I'm having is that nothing is printing to console after I have sent the request, or any kind of response for that matter. I would really appreciate any help or guidance as to what I am doing wrong
import Foundation
class URLHelper : NSObject,NSURLConnectionDelegate,NSURLConnectionDataDelegate{
var data = NSMutableData()
func sendReq(){
let urlPath: String = "http://localhost/web-service/action.php?callback=showUserDetails&uid=1"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url,cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 4)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data)
}
func connection(connection: NSURLConnection, didFailWithError error: NSError) {
println(error.description)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println(jsonResult)
}
}
var req = URLHelper()
req.sendReq()
UPDATE
<?php
//Get the action to run the coorect request
if(isset($_GET['callback'])){
$function = $_GET['callback'];
call_user_func($function);
//$function();
}else{
echo "Error: No valid callback supplied to request";
}
function showUserDetails(){
$conn = mysqli_connect("localhost", "root", "root", "service_db") or die("Error " . mysqli_error($conn));
$userid = $_GET['uid'];
$results = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM user WHERE id = $userid"));
mysqli_close($conn);
echo json_encode($results);
}
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
?>
The returned json is as follows {"id":"1","username":"tom","email":"tom_smith#gmail.com"}
For posting you don't need to make a request, just get content from the url:
var strResult:NSString
let strURL = "http://localhost/web-service/action.php?callback=showUserDetails&uid=1"
var dataURL = NSData(contentsOfURL: NSURL(string: strURL)!);
if let d = dataURL
{
strResult = NSString(data: d, encoding: NSUTF8StringEncoding)!
println(strResult)
}
Here i simply go to the url, get the content and store it in the data object, and then turning it into a string and printing it. You can also decode the JSON string (strResult) into the JSON object.
Hope it helps :)
You can use this method which have completionHandler to get back the result from your web service
func postAsync(backendMethodName:String ,body: [[String:String]], completionHandler: (resultnig:String) -> Void)
{
let session: NSURLSession = NSURLSession.sharedSession()
let urlPath: String = "\(sessionclass.connectionString)/\(backendMethodName)"
let request = NSMutableURLRequest(URL: NSURL(string:urlPath)!)
request.HTTPMethod = "POST"
request.timeoutInterval=10
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(body, options: [])
let task = session.dataTaskWithRequest(request) { data, response, error in
guard data != nil else
{
print("no data found: \(error)")
return
}
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
completionHandler(resultnig: strData as! String)
}
task.resume()
}
its take the backend method Name (in web service) and your jsonData
you can call it like this :
self.postAsync("checkConnection", body: self.alldictionariesConn, completionHandler: { (resultnig) in
print(resulting) })//resulting = result from your web service