I am quite new in the Swift 3.0 world and I'm trying to get a json full of some arrays that describe a book. This is my code:
let myUrl = NSURL(string:"http://chuadiv.ddns.net/easytoschool/fetch_book_detailed.php");
let request = NSMutableURLRequest(url:myUrl as! URL);
request.httpMethod = "POST";
let postString = "name=\(libro)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil {
print("error=\(error)")
return
}
var err: NSError?
do {
var json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray
if let parseJSON: NSArray = json {
for index in 0...parseJSON.count-1 {
let libro = parseJSON[index] as! NSArray
print((libro[0] as AnyObject).value(forKey: "id"))
print((libro[0] as AnyObject).value(forKey: "id"))
}
}
} catch {
print("error=\(error)")
return
}
}
task.resume();
"libro" is a string that I pass to the .php file with the method POST
Here is the json that is returned from the .php file that I have written:
[{"id":"19","name":"CHIMICA","author":"MASSIMO CAFARDA","school":"PILATI","price":"20","status":"Come nuovo","isbn":"0987654321123","type":"IN VENDITA","idSeller":"2","nameSeller":"Stefano","surnameSeller":"Zanella"}]
I have tried to find some material, but I can't get a json WITHOUT the name of the arrays
Can someone help me? Thank you
Related
I have found learning swift to be more or less unbearable to do anything, something that would be done in a single line in Python becomes a whole task in swift.
I am trying to return the data from a http request and cannot find a single source that explains how. The only things I can find prints the data instead of returning it, either as a dictionary (from using JSONSerialization) or simply as a string.
let url = URL(string: "url")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("error: \(error)")
} else {
if let response = response as? HTTPURLResponse {
print("statusCode: \(response.statusCode)")
}
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("data: \(dataString)")
}
}
}
task.resume()
func makePostRequest(){
let urlPath: String = "http://www.swiftdeveloperblog.com/http-post-example- script/"
var url: NSURL = NSURL(string: urlPath)!
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
var stringPost="firstName=James&lastName=Bond" // Key and Value
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
request.timeoutInterval = 60
request.HTTPBody=data
request.HTTPShouldHandleCookies=false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
if (jsonResult != nil) {
// Success
println(jsonResult)
let message = jsonResult["Message"] as! NSString
println(message)
}else {
// Failed
println("Failed")
}
})
}
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
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
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()
Here I have Tried to Sign Up the App Using Mobile Number but I cant do in correct format,I have error in Json parsing for signup the app.
Here I give the code what i am tried,
var request = NSMutableURLRequest(URL: NSURL(string: "http://app.mycompany.in/gcm/test_slim.php/register")!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
var response: NSURLResponse?
var error: NSError?
var reponseError: NSError?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
// create some JSON data and configure the request
let jsonString = "json=[{\"gsm_number\":\(Mobile),\"name\":\(Name),\"email\":\(Email),\"status\":\(Status),\"ver_code\":,\"profile_picture\":,\"device_id\":,\"gcm\":,\"is_register\":,\"thumb_image\":,\"user_baground_img\":}]"
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
// send the request
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
// look at the response
if let httpResponse = response as? NSHTTPURLResponse {
println("HTTP response: \(httpResponse.statusCode)")
println("jsonString: \(jsonString)")
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
let VerificationcodeViewController = self.storyboard?.instantiateViewControllerWithIdentifier("verificationcodeViewController") as UIViewController
self.navigationController?.pushViewController(VerificationcodeViewController, animated: true)
} else {
println("No HTTP response")
var alertView:UIAlertView = UIAlertView()
alertView.title = "Error!"
alertView.message = "Error. & Some Problem was Found"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
You can't have empty keys, try this :
let parameters = [
"gsm_number" : Mobile,
"name" : Name,
"email" : Email,
"status" : Status,
]
let jsonData = NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions.allZeros, error: nil)
let jsonString = "json=\(NSString(data: jsonData!, encoding: NSUTF8StringEncoding)!)"
You jsonString does not conform to the JSON syntax.
You can't have json= at the beginning, = isn't an allowed separator in JSON, use :
You need to wrap the string variables with double quotes (and escape them)
You can't have empty keys like that with just the value missing, you have to use null
Example of valid string for your variables:
let jsonString = "[{\"gsm_number\":\(Mobile),\"name\":\"\(Name)\",\"email\":\"\(Email)\",\"status\":\(Status),\"ver_code\":null}]"
Or with a 'json' key at the beginning like you had:
let jsonString = "{\"json\":[{\"gsm_number\":\(Mobile),\"name\":\"\(Name)\",\"email\":\"\(Email)\",\"status\":\(Status),\"ver_code\":null}]}"
Put this in a Playground and show the Assistant Editor in the "View" menu, it will help you understand:
let Mobile = 42
let Name = "James"
let Email = "test#test.com"
let Status = 200
let jsonString = "[{\"gsm_number\":\(Mobile),\"name\":\"\(Name)\",\"email\":\"\(Email)\",\"status\":\(Status),\"ver_code\":null}]"
let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
Swift 1
var err: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.allZeros, error: &err) as? [[String:AnyObject]]
if err != nil {
println(err)
} else {
println(json![0]["status"]!)
}
Swift 2
do {
if let data = data,
let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [[String:AnyObject]] {
if let status = json[0]["status"] as? Int {
print(status)
}
}
} catch let error as NSError {
print(error.localizedDescription)
}