I am trying to make my POST and GET API request methods global so that I need not repeat the call procedure repetitively. For this, I created a swift file and made two functions for POST API and GET API, but can't figure out how to pass data from calling class to the called class, and return back the response to the calling class. My code which needs to be integrated in a separate swift file is :
let request = NSMutableURLRequest(URL: NSURL(string: "http://api.quickblox.com/users.json")!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("0.1.1", forHTTPHeaderField: "QuickBlox-REST-API-Version")
request.setValue(tokenSet, forHTTPHeaderField: "QB-Token")
request.HTTPMethod = "POST"
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(dict, options: [])
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
I need to pass API Url and a request data in the form of a dictionary, to, say postApiRequest() and getApiRequest() methods. How do I create swift file for the same and call it elsewhere.
Related
Below is the URL requirement for this API: http://itaag-env-1.ap-south-1.elasticbeanstalk.com/editprofile/
according to this answer Upload image with multipart form-data iOS in Swift
I have tried below code, but i am unable to add parameters to POST Request and i am unable to call uploadImage method in viewdidload
Here is the code:
func uploadImage(paramName: String, fileName: String, image: UIImage) {
let url = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/editprofile/")
let boundary = UUID().uuidString
let deviceId: String = "HardcodeDEVICEIDforiTaag222"
let headers = ["deviceid": "deviceId","userType": "personal","key": "5fe42fb3b54543a0bab5667cf96526f8"]
let parameters: [String: Any] = ["firstName":"Satish", "lastName":"Madhavarapu","gender":"male", "ageGroup":"40-50"]
let session = URLSession.shared
var urlRequest = URLRequest(url: url!)
urlRequest.httpMethod = "POST"
urlRequest.allHTTPHeaderFields = headers as! [String : String]
// Set Content-Type Header to multipart/form-data, this is equivalent to submitting form data with file upload in a web browser
// And the boundary is also set here
urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var data = Data()
// Add the image data to the raw http request data
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
data.append("Content-Disposition: form-data; name=\"\(paramName)\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!)
data.append("Content-Type: image/png\r\n\r\n".data(using: .utf8)!)
data.append(image.pngData()!)
data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
// Send a POST request to the URL, with the data we created earlier
session.uploadTask(with: urlRequest, from: data, completionHandler: { responseData, response, error in
if error == nil {
let jsonData = try? JSONSerialization.jsonObject(with: responseData!, options: .allowFragments)
if let json = jsonData as? [String: Any] {
print(json)
}
}
}).resume()
}
in the above code i am unable to add parameters let parameters: [String: Any] = ["firstName":"Satish", "lastName":"Madhavarapu","gender":"male", "ageGroup":"40-50"] to urlRequest
And How to call uploadImage in viewDidLoad
Please help me with code
I am trying to post Audio file to an API, but I am getting an error
"*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (NSURL)'"
Here is my code:
let parameters = [fileUrl]
//create the url with NSURL
let url = NSURL(string: "httpblahblah")
//create the session object
let session = URLSession.shared
//now create the NSMutableRequest object using the url object
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
//HTTP Headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: AnyObject] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
When you create request.httpBody, you're passing in the parameters array you declared above:
let parameters = [fileUrl]
It's not clear from your code, but if fileUrl is an NSURL instead of a String, that would cause the error you see. The documentation for JSONSerialization says:
All objects are instances of NSString, NSNumber, NSArray,
NSDictionary, or NSNull.
so trying to sneak in an NSURL will definitely not work.
Assuming that your intention is to serialize fileUrl as a String, you can do that by changing the declaration to:
let parameters = [fileUrl.absoluteString!]
If you want to send the actual file data, you're not going to be able to serialize it in a JSON object. Check out this question and its answer for a good example of sending data from a file to a server. Depending on the API you're working with you may still need the JSON object for other data, and its structure will be determined by the API.
From what I understand you are trying to upload a audio file, with a URL reference instead of Data.
Get correct Data format from URL with this:
let data = FileManager.default.contents(atPath: fileUrl.path)
request.httpBody = data
I'm using API and getting json data with SwiftyJSON. I need an add token for the API. How can I do this with SwiftyJson?
My code :
let jsonData = (NSData(contentsOfURL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)! as NSData)
var readableJSON = JSON(data: jsonData, options: .MutableContainers, error: nil)
let name = readableJSON["standings"]
Normally I'm adding token with this code when I use Swift's JSON :
let url = NSMutableURLRequest(URL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)
url.addValue("mytokenishere", forHTTPHeaderField: "X-Auth-Token")
url.HTTPMethod = "GET"
Are you making a post/put with this data? Thats would make sense.
I suppose you already have made the request to get the readable data "jsonData" contains that. Since you ndicate you dont have the json data already this would probably work.
var url = NSMutableURLRequest(URL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)
url.addValue("mytokenishere", forHTTPHeaderField: "X-Auth-Token")
url.HTTPMethod = "GET"
NSURLSession.sharedSession().dataTaskWithRequest(url, completionHandler: data, response, error in {
if error == nil {
var readableJSON = JSON(data: data, options: .MutableContainers, error: nil)
let name = readableJSON["standings"]
url.HTTPBody = try! name.rawData()
NSURLSession.sharedSession().dataTaskWithRequest(url, completionHandler: data, response, error in {
//do something with his response from getting the data
})
} else {
print(error)
}
})
This is kind of a hacky way of doing it but I think its what you are going for
I managed to fetch json from my server but now I want to add extra security by way of http headers. This is how my code barely looks like for now:
let urlPath = "http://www.xxxxxxxx.com"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if ((error) != nil) {
println("Error")
} else {
// process json
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
println(jsonResult["user"])
}
})
The headers that I want to add to this request are the following:
uid, which holds an integer value
hash, which is a string
If it helps, I have another app built in Titanium framework which uses this syntax:
xhr.setRequestHeader('uid', userid);
xhr.setRequestHeader('hash', hash);
So, am basically looking for a Swift equivalent.
You are using dataTaskWithURL while you should use dataTaskWithRequest, that takes NSMutableURLRequest object as an input. Using this object you can set HTTP headers, HTTPBody, or HTTPMethod
let urlPath = "http://www.xxxxxxxx.com"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "GET" // make it post if you want
request.addValue("application/json", forHTTPHeaderField: "Content-Type")//This is just an example, put the Content-Type that suites you
//request.addValue(userid, forHTTPHeaderField: "uid")
//request.addValue(hash, forHTTPHeaderField: "hash")
let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
//do anything you want
})
task.resume()
I suggest you to use Alamofire for networking
https://github.com/Alamofire/Alamofire
It is written in Swift and is every easy to use. Have a look at that page.
Hey I'm trying to figure out this problem for quite some time so now I'm asking you guys for help.
In my Project I'm trying to send a POST request to a website with a login form to access the server.But I somehow don't manage to pass the data.
The website I'm trying to access is https://edu.sh.ch
in the Inspector of my browser I can see it needs a Post method to pass the data :
<form id="form1" name="form1" autocomplete="off" method="post" action="/uniquesigfe5a0f1f915f15b647d0b7a5306be984/uniquesig0/InternalSite/Validate.asp" onsubmit="return(SubmitForm());"></form>
here's my code:
func PostingCredentials(){
let myUrl = NSURL(string: self.manipulatedUrl)
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
// Compose a query string
let form1 = "user_name=MyUsername&password=MyPassword"
request.HTTPBody = form1.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
println("error=\(error)")
return
}
println("response = \(response)")
// You can print out response object
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
//
println("responseString = \(responseString)")
}
task.resume()
}
Note that self.manipulateUrl equals to the url which shows up when I log in normally and submit my credentials (https://edu.sh.ch/uniquesigfe5a0f1f915f15b647d0b7a5306be984/uniquesig0/InternalSite/Validate.asp)
The Post Function posts something but the response is always some sort of error page( I'm not getting any error in the code but the response of the server is an error)
So for the end my main question are :
whats the problem with my code
where do I have to send my POST method to,to the login page url or the validation url?
Thanks in advance
Some Problem with your webpage. Something is wrong in web coding. Then also you can try below code :
let form1 = "user_name=MyUsername&password=MyPassword"
let request:NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: "https://edu.sh.ch")!)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-type")
request.HTTPBody = form1.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
var str = NSString(data: data, encoding: NSUTF8StringEncoding)
//var dict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSArray
}