CTM 3d file render UIView - json

I have file with extension CTM, It is coming from server, I want to render it in UIView or UIImageView. I am receiving it as Data
guard let dict = dict, let ctm = dict["ctm"] else {
return
}
print(ctm)
key : "ctm"
▿ value : 794527 bytes
- count : 794527
▿ pointer : 0x000000014bfb8000
- pointerValue : 5569740800

Related

Fetch first element in JSON with Swift

I have a JSON string, an example is shown in the screenshot below. How can I print to the console the first element from a given array?
I've tried different options for converting a date to a string, but the string won't let me get the first element in its entirety
I recommend using a package like SwiftyJSON to work with JSON in Swift. You can add it via Swift Package Manager or CocoaPods, whichever you prefer.
Supposing to have this JSON string:
let json = "[{\"id\" : 0, \"text\" : \"hello\"},{\"id\" : 1, \"text\" : \"hi\"}]"
You can parse it as shown, and then retrieve and print to console the first item:
if let data = json.data(using: .utf8) {
if let json = try? JSON(data: data) {
print(json[0])
}
}
This will print on the console as:
{
"text" : "hello",
"id" : 0
}
Remember to import SwiftyJSON at the top of the swift file

Alamofire unexpectedly found nil while unwrapping an Optional, yet I can see the JSON

Using AlamoFire I can make an API call to my endpoint, it works and connects as expected. Using the print tools I can print the JSON response to the console and see the JSON string, but I am unable to get this string to move to the next function.
I keep getting the error:
"fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)"
My code looks like this:
func getDataForUser(Username:String, UserToken:String) {
print("Getting data for user \(Username)")
Alamofire.request(.POST, baseURL+userdataURL, parameters: ["Username": Username, "UserToken": UserToken]).response { (req, res, data, error) -> Void in
let jSONResponse: NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(data!,options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
print(jSONResponse)
if(jSONResponse["Success"] as! Bool == true) {
print("Success! API Request Worked")
self.delegate!.didReceiveAPIResults(jSONResponse)
}
}
}
The error is on line:
self.delegate!.didReceiveAPIResults(jSONResponse)
The console looks like this:
jSONResponse NSDictionary 2 key/value pairs 0x78e8d6a0
[0] (null) "Success" : "1"
[1] (null) "Response" : 2 key/value pairs
The debug screen for jSONResponse gives me data that I can drill into so I know its not nil.
Where is the nil coming from and how do I resolve?
In Swift, "1" is not equal to a Bool value of true.
It's crashing at jSONResponse["Success"] as! Bool == true. You could change this to jSONResponse["Success"] as! String == "1".
If you are able to modify the source of the API you're consuming, you're probably better of making Success a true/false JSON bool value, and leaving your Swift code as is.
My initial thoughts were that the JSON handler or API Controller were wrong.
What I had not passed was the delegate variable in the view controller setup.
EG:
api.delegate = self
Thank you to #paulvs and Eric D for pointing that out.

How can I insert my array of Objects in a JSON?

I've created an Array of Objects in Swift which has the following structure:
var myCart:[FoodItem] = []
var dump:
▿ 3 elements
▿ [0]: TablePinAdolfoTesting.FoodItem #0
- id: 5
- name: Taco
- cant: 2
▿ [1]: TablePinAdolfoTesting.FoodItem #1
- id: 6
- name: Burrito
- cant: 1
▿ [2]: TablePinAdolfoTesting.FoodItem #2
- id: 4
- name: Enchiladas
- cant: 3
I used Alamofire to get said object from my API but now, after changing them a little bit, I want to insert it into a new JSON which I created like so:
var json: JSON = ["idUser": idUser, "total_loyalty_points": totalLP, "total_price": totalPrice, "car": []]
printed json:
{
"total_price" : 50000,
"car" : [
],
"idUser" : 58,
"total_loyalty_points" : 5000
}
I have 2 issues with this...
for some reason "car" is being placed at the 2nd position even though I put it last during the JSON declaration.
The second issue is that I don't know how to place my Array of Objects within that JSON to obtain something like this:
{"idUser": (int),
"total_loyalty_points": (double),
"total_price":(double),
"car":[
{
"id": (string),
"name": (string),
"cant": (int)
}
]
}
Where "car" is an Array of Objects within that JSON. I would prefer to do this using SwiftyJSON if possible to maintain consistency but it is not a requirement.
One thing that I tried but does not work is the following
for object in cart.myCart{
var name = [String: String]()
name["id"] = object.id
name["name"] = object.name
json["car"] = JSON(name)
json["car"]["cant"] = JSON(object.cant)
}
The reason it does not work is that this will not create an array in Cart, it will just overwrite the JSON
Thanks.
For first problem there is no solution as Map or Dictionary doesn't maintain the order.
Second problem is because of you are assigning json["car"] to JSON which is a object not array of objects. Modified code is:
var cars = [[String: String]]()
for object in cart.myCart{
var name = [String: String]()
name["id"] = object.id
name["name"] = object.name
name["cant"] = object.cant
cars.append(name)
}
json["car"] = JSON(cars)

SwiftyJSON string-value empty

I have a problem with parsing JSON in Swift. I use the SwiftyJSON-framework.
My data comes from the network:
let dataString : NSString = NSString(data: data, encoding: NSUTF8StringEncoding)!;
printing this:
println("Received data: \(dataString)")
gives my JSON:
Received data: {"result":"success"}
But when I try to read the result-value:
let json = JSON(dataString);
println(json["result"].stringValue); //<-- empty string
then the output is empty. I've tried different approaches, like:
println(json[1]["result"].stringValue); //<-- empty string
println(json["result"]); //<-- prints "null"
but nothing worked so far. What am I doing wrong?
Edit:
This is server side (Java):
String response = client.isAuthenticated() ? "success" : "fail";
client.send(new JSONObject().put("result", response).toString());
To read the data I use CocoaAsyncSocket:
func socket(sock: GCDAsyncSocket!, didReadData data: NSData!, withTag tag: Int)
The error I get is:
Dictionary["result"] failure, It is not an dictionary
Edit2:
I found out that the problem is in the data:
let dataFromString = dataString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?
has a length of 22 bytes. If I set
dataString : NSString = "{\"result\":\"success\"}"
and do the same again, its length is 20 bytes. My data has two bytes 0x0014 at beginning:
<7b227265 73756c74 223a2273 75636365 7373227d> //<-- correct
<00147b22 72657375 6c74223a 22737563 63657373 227d> // <-- mine
If I remove the two byes with
dataFromString!.subdataWithRange(NSMakeRange(2, 20))
the JSON can be parsed correctly.
Edit3 (my Solution):
The problem was the DataOutputStream I used in the Java-Service. It added two bytes to my JSON. I replaced it with BufferedOutputStream and now it works as expected.
You should get the NSData from the String, and initialize the JSON object with it, here's an example:
let dataString : NSString = "{\"result\":\"success\"}"
if let dataFromString = dataString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
print(json["result"])
}
Read More: SwiftyJSON - initialization
You should construct JSON with init(data:) constructor with NSData.
Try:
let json = JSON(data: data)

How to parse JSON in Swift 2?

I have a PHP web api that returns json in the following format:
{"users":[
{"user": {id:"1","name":"ahmad"}},
...
]}
In my Swift 2 code, I am able to retrieve the data above store it in an NSArray named users
Now, I need to iterate throw each user to convert it into an object:
for user in users {
print("found: \(user)")
}
That ouputs something like:
found: {
user = {
id = 1;
name = ahmad;
};
}
but when I try to access any element of that object I get an error:
let id = user["user"]["id"] //does not work: Xcode wont compile
let id2 = user["user"]!["id"]! //does not work: Xcode wont compile
let id3 = user!["user"]!["id"]! //does not work: Xcode wont compile
Then I tried :
if let u=user["user"] { //does not work: Xcode wont compile
// do somthing
}
I put a break point at print("\(user)") to see what is going on, and here is what I found:
When I print the description of each individual user I get:
How can I access the elements of this JSON data in Swift 2?
A NSArray only holds AnyObject so you have to cast it (to Array<Dictionary<String, Dictionary<String, String>>>. Below you see the shorthand):
// this is a forced cast and you probably get runtime errors if users cannot be casted
for user in users as! [[String : [String : String]]] {
print("found: \(user)")
}