unable to print the data after encoding in swift - swift

I'm getting below error when i try to encode the data. If i print directly without encoding its printing properly
fatal error: unexpectedly found nil while unwrapping an Optional value
// get the NSURLRequestSession and get the data
let task = NSURLSession.sharedSession().dataTaskWithRequest(nsurlReq){
(data,response,error) in
// check whether there is no error
if(error==nil)
{
// println("Data \(data) ");
var encodedData = NSString(data: data, encoding: NSUTF8StringEncoding)!;
println(encodedData);
}
} //
// you need to resume the task
task.resume();

I would expect that your data has invalid encoding and that is why you're not able to print out the parsed data.

Related

Why does Swift unexpectedly insert “Optional” at the beginning of stringFromData?

I run this code on an iPad to create virtual BLE peripheral.
It starts advertising.
I run the central on iPhone.
Central detects peripheral and connects and subscribes.
Peripheral log unexpectedly has "Optional" in the log, though it's not in stringFromData.
IMAGE SHOWS stringFromData CONTENT AND LOG.........
class PeripheralViewController: UIViewController {
var packet_to_send = Data()
. . .
func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
os_log("Central subscribed to characteristic")
// Init 1st sim packet:
packet_to_send = ("antenna data chunk " + String( packet_number )).data(using: .utf8)!
let stringFromData = String(data: packet_to_send, encoding: .utf8)
os_log("initial packet_to_send %d bytes = '%s'.", packet_to_send.count, String( describing: stringFromData))
stringFromData is an Optional. When you use String(describing:) to get the description of an Optional, it will be "Optional(yourDescription)" rather than "yourDescription".
You can avoid this by converting the Optional<String> into a String using optional binding or by providing a default value.
let stringFromData = String(data: packet_to_send, encoding: .utf8) ?? ""
os_log("initial packet_to_send %d bytes = '%s'.", packet_to_send.count, stringFromData)

URLRequest - "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" Error (Swift)

I am trying to perform an HTTP POST request in swift that will send some data to my server using PHP file, but it crashes with the error
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
The token and selectedAreaNames (the error is in the first line) are just regular strings. What could be the problem?
let url = URL(string: "https://xxxxxxx.xxx/register.php/\(token)|\ (selectedAreaNames)")! //error is here...
var request = URLRequest(url: url)
request.httpMethod = "POST"
let task = URLSession.shared.dataTask(with: request) { (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()
Assuming that’s really how your URL must look, you can do:
let url = URL(string: "https://xxxxxxx.xxx/register.php")!
.appendingPathComponent(token + "|" + selectedAreasNames)
That will percent escape those portions of the URL (including the |).
That having been said, this is an exceedingly unusual format for a POST request, which usually has the data being posted inside the body of the request, not just added as another path component of the URL. And if this was a GET request, where the parameters are added to the URL, you’d generally see this after a ? in the URL, separating the path of the request from the query. And this structure of simply TOKEN|VALUES is an unusual query structure, too.

Swift get content text response after send request to web service

I know how to get data response from url. But the data response contains html source. Although I can handle it to get what I need but will be better if I know how to get only text. I use:
let task = URLSession.shared.dataTask(with: request)
{
data, response, error in guard
let data = data, error == nil else
{
// check for fundamental networking error
print(error!)
return
}
result = String(data: data, encoding: .utf8) ?? ""
}
task.resume()
You could do it like this.
let text = String(decoding: data, as: UTF8.self) // Convert data to string
.components(separatedBy: "\n") // Split string into multiple line
.first // Get the first line
Unless the endpoint has an option (like a query parameter) to return only the text, then you will get whatever the server wants to send and you will need to sort it out client side.

NSJSONSerialization error. Code=3840 "Invalid value around character 0

NSJSONSerialization.JSONObjectWithData error when using a string like "abc" but success using "123"
I do not know why.
error log
2015-11-04 17:42:02.997 SwiftJsonDemo[27196:2701028] Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
code
//var str = "123" // ok
var str = "abc" // error
let strData = str.dataUsingEncoding(NSUTF8StringEncoding)
if let d = strData {
let urlStr = String(data: d, encoding: NSUTF8StringEncoding)
do {
let json = try NSJSONSerialization.JSONObjectWithData(d, options: NSJSONReadingOptions.AllowFragments)
} catch let e {
print(e)
}
} else {
print("data error")
}
123
is a valid JSON number, so this can be read as JSON if the .AllowFragments
option is set. JSON strings must be enclosed in quotation marks:
(see http://www.json.org for the details):
"abc"
In a Swift string literal, these quotation marks are escaped with
backslashes:
let str = "\"abc\"" // OK!
let strData = str.dataUsingEncoding(NSUTF8StringEncoding)
// ...
Check with following line of code if using swift:
let contentType = response.response?.allHeaderFields["Content-Type"] as? String
Content type will be not coming as: "application/json". It implies response from server is not a valid JSON string.
Please check Response in Postman. i just solved by checking if json response is proper format or in html format
I got the same error. Turns out the mistake is in the request. The below syntax fixed the problem while adding parameters to the request.
request.setValue("Value", forHTTPHeaderField: "Key")

"contentsOfFile" returning nil, possible cause

The following returns nil when getting the content of a csv file. However, reducing the csv table to 10 rows will work properly, outputting the content of the csv file.
The original csv has about 400,000 characters arranged in 500 rows and 11 columns. What could be causing it to return nil with the original csv?
let dbPath = "/Volumes/Gios2TWD/myDB.csv"
var error: NSError?
let csvContent = NSString(contentsOfFile: dbPath, encoding:NSUTF8StringEncoding, error: &error) as String!
println(csvContent)
println(error)
I'm running XCode Version 6.1 (6A1030)
error:
Optional(Error Domain=NSCocoaErrorDomain Code=261 "The file “myDB.csv” couldn’t be opened using text encoding Unicode (UTF-8)." UserInfo=0x10050c5b0 {NSFilePath=/Volumes/Gios2TWD/myDB.csv, NSStringEncoding=4})
You need code that tests for errors something like this:
let dbPath = "/Volumes/Gios2TWD/myDB.csv"
var error: NSError?
let csvContent = NSString(contentsOfFile: dbPath, encoding:NSUTF8StringEncoding, error: &error)
if csvContent != nil {
// do something with the string
}
else {
println("error: \(error)")
}
Then try to understand any error message. Post the code and full error message to SO if you need help.
With an error message like: "couldn’t be opened using text encoding Unicode (UTF-8)" it is not a UTF-8 file. There may be corruption in the file or it many be another format. Try NSMacOSRomanStringEncoding, it is an 8-bit ASCII encoding that is very forgiving. It also might be another 8-bit ASCII encoding.
Note: Do not explicitly unwrap things unless you are 100% certain that under no circumstances they can never be nil.
Just stumbled upon this question and Zaph's answer with the recommendation to use NSMacOSRomanStringEnconding as the enconding does fix alot of issues indeed - in my case it were umlauts which caused the issue with NSUTF8StringEnconding.
Nevertheless I just wanted to add the latest Swift syntax in case you wanna catch the error and handle it properly
let csvContent: String?
do{
csvContent = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
// file could be read properly - do something with the content ...
} catch {
let nsError = error as NSError
print(nsError.localizedDescription)
}