How did swift make web requests - swift

I`m a new swifter ,so can take me some help to use swift to make web requests,thanks. Why can't it be reviewed and submitted。
//创建请求体
let param = ["moblie":"18392387159"]
let data = try! JSONSerialization.data(withJSONObject: param, options: JSONSerialization.WritingOptions.prettyPrinted)
var string = "json="
let Str = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
//拼接
string = string + Str!
let Url = URL.init(string: "http://huixin.smartdot.com:9901/GoComWebService/restful/GoComeRestful/getResetCode")
let request = NSMutableURLRequest.init(url: Url!)
request.timeoutInterval = 30
//请求方式,跟OC一样的
request.httpMethod = "POST"
request.httpBody = string.data(using: String.Encoding.utf8)
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
if (error != nil) {
return
}
else {
//此处是具体的解析,具体请移步下面
let json: Any = try! JSONSerialization.jsonObject(with: data!, options: [])
if let value = JSON(json)["status"].string {
print("状态是:\(value)")
}
print(json)
}
}
dataTask.resume()
i write like this , why it did not work !

I suggest you modify the following code
data is not recommended mandatory unpack ,I am here only to help you find the problem quickly to deal with this problem
do {
let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
print(dic)
} catch {
print(error)
}
Error returned here is
Error Domain = NSCocoaErrorDomain Code = 3840 "No value." UserInfo = {NSDebugDescription = No value.}
You may ask the parameters of the problem, check their own

Related

Returning data from URLSession in Swift

I have tried to research this issue and am unable to find a suitable fix. I attached an image of the code. I am trying to return the subscriptions array which is declared before the URLSession, and data is appended during the URLSession. However, it returns the originally declared, empty array. I added print statements so you can understand what I am talking about. It prints 2 before 1.
let request = NSMutableURLRequest(url: NSURL(string: "https://utelly-tv-shows-and-movies-availability-v1.p.rapidapi.com/lookup?term=\(searchShow)&country=us")! as URL, cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
//let json = try? JSONSerialization.jsonObject(with: data!, options: [])
//print(json)
} else {
//let httpResponse = response as? HTTPURLResponse
let decoder = JSONDecoder()
let json = try! decoder.decode(results.self, from: data!)
//print(json) (for debugging use only)
//print(httpResponse)
for item in json.results{
for each in item.locations{
subscriptions.append(each.display_name)
}
}
//Remove duplicates from array
let uniqueUnordered = Array(Set(subscriptions))
let uniqueOrdered = Array(NSOrderedSet(array: uniqueUnordered))
subscriptions = uniqueOrdered as! [String]
//Print subscriptions array
print("1: \(subscriptions)")
}
})
dataTask.resume()
print("2: \(subscriptions)")
return subscriptions

Execute a PHP call from Swift passing one parameter - does not work yet

Trying to execute a call from Swift passing one parameter to PHP and getting the result
It does not execute the PHP call... not sure why?
func getInfo(_ dataValue:String){
print("in UserModel.getInfo")
let url: URL = URL(string: urlInfoPath)!
let rq = NSMutableURLRequest(url: url)
rq.httpMethod = "POST"
let postString = "a=\(dataValue)"
rq.httpBody = postString.data(using: String.Encoding.utf8)
print("PHP postString:", postString)
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: url) {
data, response, error in
print("UserModel.getINFO FROM PHP");
if error != nil {
print("error=\(String(describing: error))")
return
}
let val = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
self.responseString = val! as String
print("responseString = ", self.responseString)
}
}

I am doing a post request where I want to type in a question and with the post request get the most common answer

I have done my Post-request but I am unsure about how to make it possible to send a full question and to get the most common answers back to my app.
I am in such a big need of this code in my program so would love to get some examples on how to make it work
Have tried to right the question into the parameters with a "+" instead of space which resulted into nothing.
#IBAction func GetAnswer(_ sender: Any) {
let myUrl = URL(string: "http://www.google.com/search?q=");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
let postString = questionAsked;
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(String(describing: error))")
return
}
print("response = \(String(describing: response))")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let answer = parseJSON[" Answer "] as? String
self.AnswerView.text = ("Anwer: \(String(describing: answer))")
}
} catch {
print(error)
}
}
task.resume()
}
You do not use google.com/search, please check the api documentation
Paste following in Playground, should give a good start
struct Constants {
static let apiKey = "YOUR_API_KEY"
static let bundleId = "YOUR_IOS_APP_BUNDLE_ID"
static let searchEngineId = "YOUR_SEARCH_ENGINE_ID"
}
func googleSearch(term: String, callback:#escaping ([(title: String, url: String)]?) -> Void) {
let urlString = String(format: "https://www.googleapis.com/customsearch/v1?q=%#&cx=%#&key=%#", term, Constants.searchEngineId, Constants.apiKey)
let encodedUrl = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
guard let url = URL(string: encodedUrl ?? urlString) else {
print("invalid url \(urlString)")
return
}
let request = NSMutableURLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
request.httpMethod = "GET"
request.setValue(Constants.bundleId, forHTTPHeaderField: "X-Ios-Bundle-Identifier")
let session = URLSession.shared
let datatask = session.dataTask(with: request as URLRequest) { (data, response, error) in
guard
error == nil,
let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String : Any]
else {
// error handing here
callback(nil)
return
}
guard let items = json["items"] as? [[String : Any]], items.count > 0 else {
print("no results")
return
}
callback(items.map { ($0["title"] as! String, $0["formattedUrl"] as! String) })
}
datatask.resume()
}
Usage
googleSearch(term: "George Bush") { results in
print(results ?? [])
}
Create a new search engine using following url
https://cse.google.com/cse/create/new
If you would like search entire web, use following steps
edit your engine using https://cse.google.com/cse/setup/basic?cx=SEARCH_ENGINE_ID
remove any pages listed under Sites to search
turn on Search the entire web

Send dictionary data via HTTP POST method in Swift

I'm trying to make an HTTP post request with params set in a dictionary here's my dict
let parameters = [
["name": "tag","value": "login"],
["name": "email","value": "s#s.com"],
["name": "password","value": "aaaa"]
]
but I don't to know how to access it in hers's my complete request function
func data_request(_ url:String)
{
let parameter = [
["name": "tag","value": "login"],
["name": "email","value": "s#s.com"],
["name": "password","value": "aaaa"]
]
let url:NSURL = NSURL(string: url)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
let paramString = parameter?
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
print("error")
return
}
if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
{
print(dataString)
}
}
task.resume()
}
Need to convert dictionary to json string like below:
let jsonData = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
After that pass to the http.Body
// insert json data to the request
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = jsonData
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: []) as? [String:AnyObject]
print("Result -> \(result)")
} catch {
print("Error -> \(error)")
}
}
task.resume()
return task
} catch {
print(error)
}
You need to convert the Dictionary into Data and set it to httpBody
you could solve in this way
let paramData = try? JSONSerialization.data(withJSONObject: parameter, options: [])
request.httpBody = paramData

swift URLRequest doesn't send parameters

In the code below
let bodyData = "?sub=\(id)&name=User&email=test#test.com"
let url = NSURL(string: "https://httpbin.org/get");
let request:NSMutableURLRequest = NSMutableURLRequest(url:url as! URL)
request.httpMethod = "GET"
request.httpBody = bodyData.data(using: String.Encoding.utf8);
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main)
{
(response, data, error) in
if let HTTPResponse = response as? HTTPURLResponse {
let statusCode = HTTPResponse.statusCode
if statusCode == 200 {
// Yes, Do something.
let json = try? JSONSerialization.jsonObject(with: data!, options: [])
if let dictionary = json as? [String: Any] {
let args = dictionary["args"]
NSLog("args:\(args)")
for (key, value) in dictionary{
NSLog("key:\(key) value:\(value)")
}
}
}
}
}
id is a string passed in to the function.
It has valid data returned, but the test site/url also returns in json format any parameters you send it. But this snippet of code seems to not be sending the query parameters defined in bodyData and I can't figure out why.
If a GET request is used the parameters are appended to the URL and an explicit URLRequest is not needed at all.
This code is native Swift 3 and uses contemporary API:
let id = 12
let bodyData = "?sub=\(id)&name=User&email=test#test.com"
let url = URL(string: "https://httpbin.org/get" + bodyData)!
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any],
let args = json["args"] as? [String:Any] {
print("args:\(args)")
for (key, value) in args{
print("key:\(key) value:\(value)")
}
}
} catch {
print(error)
}
}.resume()