Convert Dictionary to Base64: error Segmentation fault 11 - swift

I am trying to create JSON Web Token using JSONSerialization class, Swift 3 and Xcode 8.1, but my project fails to build with error:
Command failed due to signal: Segmentation fault 11.
Anyone knows why my code is not correct?
If I comment out this code from the project, the project builds.
let customerError = "Custom Error"
enum headerError: Error {
case customerError
}
let headerJWT: [Dictionary] = ["alg":"RS256","typ":"JWT"]
//Convert headerJWT to Data
do {
let headerJWTData: Data = try? JSONSerialization.data(withJSONObject:headerJWT,options: JSONSerialization.WritingOptions.prettyPrinted)
} catch headerError.customerError {
print("could not make data")
}
//Convert headerData to string utf8
do {
let headerJWTString = try String(data: headerJWTData,encoding:String.Encoding.utf8) as! String
} catch {
print("string could not be created")
}
//Convert headerJWTString to base64EncodedString
do {
let headerJWTBase64 = try Data(headerJWTString.utf8).base64EncodedString()
} catch {
"base64 could not be created"
}

Once you create the Data from using JSONSerialization, you simply use the method from Data to get a base64 encoded string.
let headerJWT: [Dictionary] = ["alg":"RS256","typ":"JWT"]
do {
let headerJWTData: Data = try? JSONSerialization.data(withJSONObject:headerJWT,options: JSONSerialization.WritingOptions.prettyPrinted)
let headerJWTBase64 = headerJWTData.base64EncodedString()
} catch headerError.customerError {
print("could not make data")
}
You can pass different options to base64EncodedString() depending on what format you need the base64 string to be in.

Related

Does anyone know how to write a file using Swift Script?

I am currently trying to write a script with Swift.
In the first run, the content was not written to the file.
But the second time it worked the same way.
Does anyone know how to solve it?
This is the code I wrote now.
func write_code_in_file(_ file_path: String,_ codes: String) {
let write_code = Process()
write_code.executableURL = URL(fileURLWithPath: "/usr/bin/env")
write_code.arguments = ["touch", current_path+file_path]
do {
try write_code.run()
} catch {
print("⚠️ Error - write code in file")
}
if let data: Data = codes.data(using: String.Encoding.utf8) { // String to Data
do {
try data.write(to: URL(fileURLWithPath: current_path + file_path))
} catch let e {
print("⚠️"+e.localizedDescription)
}
}
}
And the result value when you run it.

Issue with UserDefaults (converting data to array and back)

What I want to do:
I want to get an array from UserDefaults that I saved beforehand and append a custom object to it. Afterwards I want to encode it as a Data-type again and set this as the UserDefaults Key again.
My problem:
The encoding part is what is not working as intended for me.
It says: -[__SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x60000011a540
But I do not know how to fix this.
Below is my code for more context:
do {
let decoded = defaults.object(forKey: "ExArray") as! Data
var exo = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(decoded) as! [Exerc]
exo.append(datas[indexPath.row])
let enco = try NSKeyedArchiver.archivedData(withRootObject: exo, requiringSecureCoding: false) <- Here is the error
defaults.set(enco, forKey: "ExArray")
} catch {
print("Error encoding custom object NOSEARCHO")
}
This is how Exerc looks:
struct Exerc: Codable {
var title: String
var exID: String
}
Seems like you are not using the archiver features, so why don't you just use the codable?
do {
let key = "ExArray"
let decoded = defaults.data(forKey: key)!
var exo = try JSONDecoder().decode([Exerc].self, from: decoded)
exo.append(datas[indexPath.row])
let enco = try JSONEncoder().encode(exo)
defaults.set(enco, forKey: key)
} catch {
print("Error encoding/decoding custom object NOSEARCHO", error)
}
It just a simple refactored MVP of the original code, but you can even work a bit on this and make it human readable right in the plist file!

replacingOccurrences works in Playground, fails in compiled macos app

I am sending a POST request to a server and get a response back. So far so good. When I convert the data to a (very long) string the response contains backslashes, which shouldn't be there.
“
Here is the snippet that handles the request:
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let response = response, let data = data {
print(response)
let str = String(data: data, encoding: .utf8)
let replaced = str?.replacingOccurrences(of: "\\", with: "")
print(replaced)
} else {
print(error)
}
}
Trying to replace the '\' character with
let replaced = str?.replacingOccurrences(of: "\", with: "")
works in the Playground, however a debug runtime it does not strip the backward slashes.
Question: Is there a bug in Xcode? In 2018 with Xcode 9 there was such a bug. I am using Xcode 11.3 on macOS 10.14 compiling a macOS app.
Second question, is there another way to decode the data than using
let str = String(data: data, encoding: .utf8)
Thanks
Figured it out. Needed to decode data, not encode.
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let response = response, let data = data {
print(response)
let str = String(decoding: data, as: UTF8.self)
print (str)
} else {
print(error)
}
}

Alamofire, Swift: What could be causing this error?

What could be causing this error?
All of a sudden out of nowhere I started getting the error below. I have reinstalled the cocoapod, cleaned the build folder, and reinstalled the app already and none of that has fixed the error.
ERROR: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
CODE:
let recoverUrl = "http://www.website.com/recover.php?email=\(emailData)&local=application"
let urlEncodedString = recoverUrl.replacingOccurrences(of: " ", with: "%20")
parseRecover(url: urlEncodedString)
//////////////
func parseRecover(url : String){ AF.request(url).responseJSON(completionHandler: { response in self.parseData(JSONData: response.data!) }) }
func parseData(JSONData : Data){
do {
var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONObject
if let recoverJSON = readableJSON["Recover"] as? [JSONObject] {
for i in 0..<recoverJSON.count {
let JSON = recoverJSON[i]
let status = JSON["status"] as! String
let message = JSON["message"] as! String
if status == "Error" {self.Alert01("\(message)")}
else if status == "Success" { self.Alert02("\(message)") }
}}}
catch { print(error) }
}
ERROR IS OCCURING AT:
func parseRecover(url : String){ AF.request(url).responseJSON(completionHandler: { response in self.parseData(JSONData: response.data!) }) }
There's no guarantee that a response has data, so force unwrapping the value can lead to crashes. I suggest you create Decodable types to parse your responses and use Alamofire's responseDecodable method to handle your responses.
Additionally, even if you don't adopt Decodable, responseJSON already parses your response Data using JSONSerialization, so you can just access the response.result to see the output.
SOLVED: The issue was within my php file. I was using $_GET[''] and it should have been a $_POST[''] or $_REQUEST['']

How to convert String to JSON in Swift

I am receiving text from a web socket. And I want to convert the text to JSON.
Text received from the socket:
{'id': 920, 'location': {'lat': 11.0368754733495, 'lon': -47.203396772120247}}
Tried this:
func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
print("got some text: \(text)")
let data = Data(text.utf8)
do {
// make sure this JSON is in the format we expect
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
// try to read out a string array
if let id = json["id"] as? Int {
print(id)
}
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
But I am getting Failed to load: The data couldn’t be read because it isn’t in the correct format. error.
This is not valid JSON. The keys must be wrapped in double quotes.
You can replace the single quotes with double quotes on the fly
let data = Data(text.replacingOccurrences(of: "\'", with: "\"").utf8)
Side note:
Never print .localizedDescription in JSONSerialization/JSONDecoder catch blocks. And bridge casting to NSError is redundant
catch {
print("Failed to load:", error)
}