what i've to do for getting, posting and checking data from a DB (MySQL) using swift?
Can I only create the php pages and contact them or there's a way to manage them? If yes, how?
(Sorry for my english)
Yes you need a php script
In your swift file:
var bodyData = "name=value" //To get them in php: $_POST['name']
let URL: NSURL = NSURL(string: "URL TO YOUR PHP FILE")
let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
var output = NSString(data: data, encoding: NSUTF8StringEncoding) // new output variable
var array = self.JSONParseArray(output)
}
in php:
function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
$status_header = 'HTTP/1.1 ' . $status;
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
}
$name = $_POST['name']; // Like in the bodyData var
//Doing sql things
$result = array(
"result" => "VARIABLE TO SEND BACK"
);
sendResponse(200, json_encode($result));
And if you wan't to get the result in an array use this function:
func JSONParseArray(jsonString: String) -> Array<String> {
var e: NSError?
var data: NSData!=jsonString.dataUsingEncoding(NSUTF8StringEncoding)
var jsonObj = NSJSONSerialization.JSONObjectWithData(
data,
options: NSJSONReadingOptions(0),
error: &e) as Array<String>
if e == 0 {
return Array<String>()
} else {
return jsonObj
}
}
Related
Will be grateful for help
I get server response with strange dictionary format
Data: {
"featureHelpshift" = "true";
"featureAppleTVSynchronisation" = "false";
"featureDirectPlay" = "true";
"googleLoginSwitchOn" = "true";
"serverVersion" = "6.11.1";
"facebookLoginSwitchOn" = "true";
"allAvailableWorlds" = (
{
"name" = "\U0420\U043e\U0441\U0441\U0438\U044f 16 (\U043d\U043e\U0432\U044b\U0439)";
"mapURL" = "https://backend2.lordsandknights.com/maps/LKWorldServer-RU-16";
"worldStatus" = {
"id" = "3";
"description" = "online";
};
"country" = "RU";
"language" = "ru";
"id" = "190";
"url" = "https://backend2.lordsandknights.com/XYRALITY/WebObjects/LKWorldServer-RU-16.woa";
},...
first i try to serialize this response to JSON with swiftyJSON and json serializer
Than i get response as Data and parse it to String
func some () {
Alamofire.request(serverRequest, method: .post, parameters: parameters).responseData { response in
if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) {
//print("Data: \(utf8Text)") //- server response that shown above i print here
print("Change->")
let str = self.responseToJsonParsing(stringResponse: utf8Text)
print("Data: \(str)")
}
}
}
i try to lead my data string response to JSON string format, create function for parsing:
func responseToJsonParsing(stringResponse: String) -> String {
var parseResponse = stringResponse.replacingOccurrences(of: ";\n\t\t}", with: "\n\t\t}", options: .literal)
parseResponse = parseResponse.replacingOccurrences(of: ";\n\t\t\t}", with: "\n\t\t\t}", options: .literal)
parseResponse = parseResponse.replacingOccurrences(of: ";\n\t}", with: "\n\t}", options: .literal)
parseResponse = parseResponse.replacingOccurrences(of: ";\n}", with: "\n}", options: .literal)
parseResponse = parseResponse.replacingOccurrences(of: ";", with: ",")
parseResponse = parseResponse.replacingOccurrences(of: "=", with: ":")
parseResponse = parseResponse.replacingOccurrences(of: "(", with: "[")
parseResponse = parseResponse.replacingOccurrences(of: ")", with: "]")
return parseResponse
}
after parsing i still cant create JSON or Dictionary
Trying to make a GET request with Swift 3 and Xcode8 but not having much luck outputting data I received back from my GET request to the Main.Storyboard either in a label or a text field all I get is all the returned JSON in the console in Xcode8.
There is a snippet of JSON that is returned with my request in Xcode8 which I have attached below for reference. I can access "#encoding" and "#version" but everything else is not able to be accessed and I am not able to figure out why. If this was a web based setup I could just declare a variable and then set it equal to someObject.petfinder[1].shelters etc...
This is my code that is making the request, taking a zipcode from an input field and then building the url and returning it which then is using NSDictionary.
The error I get back in the console is:
"fatal error: unexpectedly found nil while unwrapping an Optional value
2017-06-20 12:15:49.392688 PetFinder[47445:9486946] fatal error: unexpectedly found nil while unwrapping an Optional value"
// SEND HTTP GET REQUEST
// DEFINE SERVER SIDE SCRIPT URL
let scriptUrl = "https://api.petfinder.com/"
let methodType = "shelter.find"
let apiKey = "?key=0000000000000000000000000"
let urlWithParams = scriptUrl + methodType + apiKey + "&location=\(shelterZip)&format=json"
// CREATE NSURL Object
let myUrl = NSURL(string: urlWithParams)
// CREATE URL REQUEST
let request = NSMutableURLRequest(url:myUrl! as URL);
// REQUEST METHOD - GET / POST
request.httpMethod = "GET"
// RUN HTTP REQUEST
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error \(error!)")
return
}
// PRINT OUT RESPONSE STRING
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(String(describing: responseString))")
// CONVERT RECEIVED JSON TO NSDictionary
do {
if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
// Print out dictionary
print(convertedJsonIntoDict)
// Get value by key
let shelterName = convertedJsonIntoDict["shelters"] as? [String: Any]
for(key, pair) in convertedJsonIntoDict {
print("-->\(key) \(pair)")
}
print(shelterName!)
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
task.resume()
}
// SNIPPET OF RETURNED JSON FROM THE TOP
{
"#encoding" = "iso-8859-1";
"#version" = "1.0";
petfinder = {
"#xmlns:xsi" = "http://www.w3.org/2001/XMLSchema-instance";
"#xsi:noNamespaceSchemaLocation" = "http://api.petfinder.com/schemas/0.9/petfinder.xsd";
header = {
status = {
code = {
"$t" = 100;
};
message = {
};
};
timestamp = {
"$t" = "2017-06-20T16:15:49Z";
};
version = {
"$t" = "0.1";
};
};
lastOffset = {
"$t" = 25;
};
shelters = {
shelter = (
{
address1 = {
};
address2 = {
};
city = {
"$t" = Nebraska;
};
country = {
"$t" = US;
};
email = {
"$t" = "wooffun#woof.net";
};
fax = {
};
id = {
"$t" = NE117;
};
latitude = {
"$t" = "13.004";
};
longitude = {
"$t" = "-31.449";
};
name = {
"$t" = WOOF COMPANY;
};
phone = {
};
state = {
"$t" = NE;
};
zip = {
"$t" = 68001;
};
},
First of all – and as always
Do not use NSDictionary in Swift. You throw away the type information.
Do not use Foundation classes like NSURL, NS(Mutable)URLRequest if there is a native Swift counterpart.
A GET request does not require an URLRequest at all, it's the default.
Second of all lets use a type alias for convenience reasons.
typealias JSONDictionary = [String:Any]
This code is supposed to extract the keys and values you are looking for
let scriptUrl = "https://api.petfinder.com/"
let methodType = "shelter.find"
let apiKey = "?key=0000000000000000000000000"
let urlWithParams = scriptUrl + methodType + apiKey + "&location=\(shelterZip)&format=json"
// CREATE NSURL Object
let myUrl = URL(string: urlWithParams)!
// RUN HTTP REQUEST
let task = URLSession.shared.dataTask(with: myUrl) { data, response, error in
if error != nil {
print("error \(error!)")
return
}
// CONVERT RECEIVED JSON TO NSDictionary
do {
if let rootDictionary = try JSONSerialization.jsonObject(with: data!) as? JSONDictionary,
let petfinder = rootDictionary["petfinder"] as? JSONDictionary {
// Get value by key
if let shelters = petfinder["shelters"] as? JSONDictionary,
let shelter = shelters["shelter"] as? [JSONDictionary] {
for item in shelter {
for (key, value) in item {
print("-->\(key) \(value)")
}
}
}
}
} catch {
print(error.localizedDescription)
}
}
task.resume()
In my swift 2 app i would like to make an http-post-request to get data of my mysql database. After that I would like to write this data into my core data.
I have the code part for request and write.
How do I get the following structure.
Request Data
if request data complete write in into core data
Could this be the correct thing?
This is my SyncMYSQL function in my Sync.swift file.
class func SyncMYSQL() {
print("START SYNC MYSQL")
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let defaults = NSUserDefaults.standardUserDefaults()
let request = NSMutableURLRequest(URL: NSURL(string: "https://xxx")!)
request.HTTPMethod = "POST"
let postString = "userid=12"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
// if no internet connection
guard error == nil && data != nil else {
print("error=\(error)")
return
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
let fetchRequest = NSFetchRequest(entityName: "ITEMS")
fetchRequest.returnsObjectsAsFaults = false
do {
let results = try managedObjectContext!.executeFetchRequest(fetchRequest)
for managedObject in results {
let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
managedObjectContext!.deleteObject(managedObjectData)
}
} catch let error as NSError {
print("Detele all data in ITEMS error : \(error) \(error.userInfo)")
}
var x = 0
while (x < responseString.count ) {
let newItem = NSEntityDescription.insertNewObjectForEntityForName("ITEMS", inManagedObjectContext: managedObjectContext!) as! CoreData_ITEMS
newItem.name = responseString[x]
x++
}
dispatch_sync(dispatch_get_main_queue(),{
print("FINISH MYSQL")
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
});
}
task.resume()
}
This function i call from my view controller like this way:
func RequestData() {
Sync.SyncMYSQL()
print ("Start Core Data")
let fetchRequest = NSFetchRequest(entityName: "ITEMS")
do {
try data = managedObjectContext!.executeFetchRequest(fetchRequest) as! [CoreData_ITEMS]
} catch { }
Table.reloadData()
}
You should use closure blocks as callback when the operation ends
class func SyncMYSQL(onSuccess: ()->()){
// your custom events
// your custom events
// your custom events
if MYSQLisSynced == true {
// when MYSQL is synced you can call the success block
onSuccess()
}
}
In other file when you call the function SyncMYSQL() you have to specify the on success block
SyncMYSQL { () -> () in
//custom callback actions
}
I am trying to get an array of values from a JSON file using Swift. I found the way to get the values printed when a button is pressed using a IBAction method.
The Function is printing the array fine the first time the button is pressed however, if I press the button again the app crashes giving the error:
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
The array that I get the first time from printing jsonResult looks Like:
1: {
Age = 30;
Email = "info#example.com";
Location = Rome;
MyText = "Design Agency";
Name = Admin;
Password = 123456;
REF = 002;
"Reg_Date" = "2015-07-28";
Sex = Male;
Surname = "Mobile App"; }
2: {
Age = 30;
Email = "example#gmail.com";
Location = London;
MyText = "aaaaaaaaa";
Name = Andrew;
Password = 123456;
REF = 001;
"Reg_Date" = "2015-07-28";
Sex = Male;
Surname = Nos; }
It seems that the second time I call the function, it cannot read the file anymore.
Whats wrong with my code? Do I need to close the connection?
#IBAction func login_button(sender: AnyObject) {
searchFunction()
}
func searchFunction() {
var tempUrlValue = loginJsonResults.stringForKey("loginJsonResults")
let urlPath: String = "https://example.com/iOS/users_result.json"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
var err: NSError
var jsonResult: NSMutableArray = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSMutableArray
//Call jsonResult Values
var temporaryString: AnyObject = jsonResult[1]
for (index, jsonResult) in enumerate(jsonResult){
println("\(index + 1): \(jsonResult)")
countUsers++
}
println(countUsers)
}
I'd like to get token as String type, however the following code returns error as " "String" is not convertible to "Void" ".
Could you tell me what is the problem?
In order to parse JSON, I used SwiftyJSON
func authentication() -> String {
let request = NSMutableURLRequest(URL: NSURL(string: "https://~~~/v2/authenticate/api")!)
request.HTTPMethod = "POST"
var loginID = "my_ID"
var apiKey = "my_APIKEY"
var postString:NSString = "login_id=\(loginID)&api_key=\(apiKey)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().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)")
let json = JSON(data:data)
if let token = json["auth_token"].stringValue{
println("\(token)")
return token ///Error Here
}
}
task.resume()
}
※Edited Jan6th 7:50(GMP+9hr)
I edited as following, however I got error as ""Use of unresolved identifier "tokenString".
Please tell me how to solve the problem.
func authentication() -> String {
let request = NSMutableURLRequest(URL: NSURL(string: "https://~~~/v2/authenticate/api")!)
request.HTTPMethod = "POST"
var loginID = "my_ID"
var apiKey = "my_APIKEY"
var postString:NSString = "login_id=\(loginID)&api_key=\(apiKey)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().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)")
let json = JSON(data:data)
if let token = json["auth_token"].stringValue{
println("\(token)")
tokenString = self.didReceiveAuthToken(token)///Edited
}
}
task.resume()
return tokenString
}
func didReceiveAuthToken(token : String) ->String{
return token
}
The dataTaskWithRequest closure takes a return type of void. Your method that returns a string ends immediately after task.resume() is executed and does not return anything.
Your basic problem is that you're applying synchronous thinking to an asynchronous task. One easy suggestion is to have authentication() return void (ie, nothing), and then make a separate method like didReceiveAuthToken(token : String) that is called by your completion handler when the token is received.