What is the best way to upload and download an image to Parse.com using REST API?
I tried to encode to base64, but can't seem to get it to cast back to UIImage I get the JSON NSData. Tried to decode back but didn't work.
After testing and extensive research, I found the solution:
After you cast the UIImage to NSData, you need to encode to base64 String and then upload the image to Parse.com using REST API see Using Swift in an iOS Application to Upload an Image to a RESTful API.
Next stage when you call a GET request to Parse.com, use the below to decode the base64 and cast it back to UIImage.
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) in
if (error == nil) {
do {
let imageJSONDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]
let base64String = imageJSONDictionary!["imageKey"] as! String
let imageData:NSData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))!
self.imageView.image = UIImage(data: imageData)
} catch {
}
} else {
print("ERROR: \(error)")
}
})
task.resume()
Related
So, I'm trying to make a very simple watchOS app in XCode. It consists of a button, two labels and a separator between the two labels. It is a digital assistant app, and needs to interface with Dialogflow (https://dialogflow.com).
The button calls the presentTextInputController function, and I want to use that result as a query to my Dialogflow agent.
I need to make an HTTP request, which in JS would look more like this:
{
url:"https://api.api.ai/v1/query",
method:"post",
body:JSON.stringify({query:"userInput",lang:"en-US",sessionID:"yaydevdiner"}),
headers:{
contentType:"application/json; charset=utf-8",
Authorization:"Bearer <auth_token>"
}
}
The response is a JSON object, and I need to access the jsonObject["result"]["speech"] value as a String to use Label.setText()
Everything I've tried has given errors about type Any and other such things. I also haven't been able to do much debugging since the print output isn't showing up in XCode.
I must mention that I'm an extreme beginner to Swift, and I am not good at handling their types and casting and unpacking and things like that.
Could someone show me how I might handle this request and the subsequent processing of the JSON?
Here is my current code:
//HTTP Request
let parameters = [
"query":name![0] as? String,
"lang":"en-US",
"sessionID":"yaydevdiner"
];
//create the url with URL
let url = URL(string: "https://api.api.ai/v1/query")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer f786fef55008491fb8422cea2be85eb1", forHTTPHeaderField: "Authorization")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject (with: data, options: .mutableContainers) as? [String:Any] {
self.Response.setText(json["result"]["string"]);
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}
Response is a text label.
This code gives me an error saying I should have a question mark between
json["result"] and ["speech"]. When I do this, it gives me another error saying "Type Any has no subscript members".
Ok, I figured it out.
Because XCode automatically makes an iOS app with the watchOS app, I decided to try debugging in the iOS app until I got the HTTP request and JSON parsing right.
Inside the JSONSerialization if statement, I had to add another if statement:
if let result = responseJSON["result"] as? [String:Any]{
self.Response.setText(result!["speech"] as? String ?? "Network error Occurred")
}
Thanks for the help from vadian!
i am storing images on mysql db as a medium blob, i am sending web request from ios device to nodejs server which fetches images from mysql and sends them back to the ios device in the response, i am having trouble parsing the data send back from the nodejs server. What i need to accomplish is transform the data that is sent back into UIImages so i can use them in my ios app. Also i know its not ideal to store images in database but thats what im doing. Any help is appretiated.
let task = session.dataTask(with: request)
{ data, response, error in
if error != nil
{
print("error in web request")
}
else
{
DispatchQueue.main.async
{
self.parseWebPhotos(stuff: data) //stoer results in class member
/*need to dispatch this to main queue since this is in closure, so needs to update ui so needs to
run on the main thread*/
self.getPhotosFinished()
}
}
}//completion handler end
func parseWebPhotos(stuff: Data?)
{
if stuff != nil
{
if let dataAsAny: NSArray = try? JSONSerialization.jsonObject(with: stuff!, options: .mutableContainers) as! NSArray//checks that parsing didnt return error
{
let dic = dataAsAny[0] as! [String: AnyObject] //dictionary of all the pictures
let pic0 = dic["pic0"] as! [String: AnyObject] //dictionary of pic0
let data = pic0["data"] as! NSArray
NotificationCenter.default.post(name: Notification.Name("foo"), object: nil)
}
}
}
I am trying to learn Swift. One of my projects is to try to retrieve JSON data from an internal web service (a group of Python CGI scripts) and convert it into a Swift object. I can do this easily in Python, but I am having trouble doing this in Swift. Here is my playground code:
import UIKit
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
let endpoint: String = "http://pathToCgiScript/cgiScript.py"
let url = NSURL(string: endpoint)
let urlrequest = NSMutableURLRequest(URL: url!)
let headers: NSDictionary = ["User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)",
"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"]
urlrequest.allHTTPHeaderFields = headers as? [String : String]
urlrequest.HTTPMethod = "POST"
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(urlrequest) {
(data, response, error) in
guard data != nil else {
print("Error: did not receive data")
return
}
guard error == nil else {
print("Error calling script!")
print(error)
return
}
do {
guard let received = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as?
[String: AnyObject] else {
print("Could not get JSON from stream")
return
}
print(received)
} catch {
print("error parsing response from POST")
}
}
task.resume()
I know making a 'POST' to retrieve data may look odd, but that is how the system is set up. I keep on getting:
Could not get data from JSON
I checked the response, and the status is 200. I then checked the data's description with:
print(data?.description)
I got an unexpected result. Here is a snippet:
Optional("<0d0a5b7b 22535441 54555322 3a202244 6f6e6522 2c202242 55535922...
I used Mirror, and apparently the type is NSData. Not sure what to make of this. I have tried to encode the data with base64EncodedDataWithOptions. I have tried different NSJSONReadingOptions as well to no avail. Any ideas?
Update:
I used Wireshark to double check the code in the Playground. Not only was the call made correctly, but the data being sent back is correct as well. In fact, Wireshark sees the data as JSON. The issue is trying to turn the JSON data into a Swift object.
I figured out what was wrong. I was casting to the wrong type. This is the new code:
guard let received = try! NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as? [AnyObject]
The JSON was not returning an array of dictionaries but an array of objects.
I'm trying to retrieve some data from an URL thanks to JSON. Here's my swift code:
// get symbol asked
let symbol = symbolField.text!
// define URL
let url = NSURL(string: "http://yahoojson.gobu.fr/symbol.php?symbol=\(symbol)")!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
if let urlContent = data {
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers)
print(jsonResult)
} catch {
print("Error JSON")
}
}
}
task.resume()
Everything seems to work fine, but the "do-try-catch" always prints "Error JSON". My code seems unable to convert my URL content into actual JSON. Any idea what I am doing wrong?
The URL returns html/javascript not pure json.
Paste the URL into your browser and look at the source code.
A side note: replace
print("Error JSON")
with
print(error)
to get more specific error information
I am trying to read json date from url and parse it in Tableview using swift. how can I make variable "jsonResult " as global ?
or please guide me how can I populate the tableview with this data from json.
let urlPath = "http://omanevents.net/OmanEventsApp/testPullDate.php"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
if (error != nil) {
println("error")
}else {
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
for var index = 0; index < jsonResult["Events"]?.count ; ++index {
println(jsonResult["Events"]?[index]["Location"])
}
}
})
task.resume()
I would highly recommend that you have a look at this tutorial.
http://www.raywenderlich.com/85578/first-core-data-app-using-swift
It shows you how to deal with core data but in the example it uses adding things to tableView, and saving data for use of the app at later stages. Ray Wnderlich is a great website.