Text Detection problems with Google Vision - ios

Not sure what the issues is as my code just stopped working overnight, but the text detection on Google Vision is either returning nil or returning words that are non-existent on the subject.
Here's my request function:
func createRequest(with imageBase64: String) {
let jsonRequest = [
"requests": [
"image": [
"content": imageBase64 ],
"features": [
["type": "TEXT_DETECTION"],
["type": "IMAGE_PROPERTIES"]
]
]
]
let jsonData = try? JSONSerialization.data(withJSONObject: jsonRequest)
var request = URLRequest(url: googleURL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(Bundle.main.bundleIdentifier ?? "", forHTTPHeaderField: "X-Ios-Bundle-Identifier")
request.httpBody = jsonData
DispatchQueue.global().async {
let task: URLSessionDataTask = self.URLsession.dataTask(with: request) { (encodedObject, response, error) in
guard let data = encodedObject, error == nil else {
print(error?.localizedDescription ?? "no data")
return
}
self.analyzeResults(data)
}
task.resume()
}
}
Part of my analyze results function:
func analyzeResults(_ data: Data) {
DispatchQueue.main.async {
guard let response = try? JSONDecoder().decode(Root.self, from: data) else { return }
guard let responseArray = response.responses else { return }
print(response)

Related

Passing an array of parameters as a request body in swift

I'm trying to pass an array of parameters that looks like this:
{
"watermarks": [
{
"email" : "correo_user",
"event_type" : "app",
"watermark" : "marcaAgua",
"date" : "date",
"location" : "location",
"segment" : 1,
"time" : "time",
"country" : "country",
"city" : "city"
}
]
}
I don't know how to pass it as an array of objects because I have never done it before. This is the code that I'm currently using:
func marcaAgua(parameters: [String: Any],
completion: #escaping (Result<[MarcaAguaResData], Error>)-> Void) {
let urlString = baseUrl + "events"
guard let url = URL(string: urlString) else {
completion(.failure(NetworkingError.badUrl))
return
}
var request = URLRequest(url: url)
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
request.httpMethod = "POST"
request.setValue("Bearer \(token_login)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
guard let unwrappedResponse = response as? HTTPURLResponse else {
completion(.failure(NetworkingError.badResponse))
return
}
switch unwrappedResponse.statusCode {
case 200 ..< 300:
print("success")
default:
print("failure")
}
if let unwrappedError = error {
completion(.failure(unwrappedError))
return
}
if let unwrappedData = data {
print("QQQQQ")
print(unwrappedData)
do{
let json = try JSONSerialization.jsonObject(with: unwrappedData, options:.allowFragments)
if let successRes = try? JSONDecoder().decode([MarcaAguaResData].self, from: unwrappedData){
completion(.success(successRes))
}else{
let errorResponse = try JSONDecoder().decode([MarcaAguaErrorResponse].self, from: unwrappedData)
print("Error \(errorResponse)")
completion(.failure(errorResponse as! Error))
}
}catch{
print("AAA")
completion(.failure(error))
}
}
}
}
task.resume()
}
When I pass the parameters to the function when I call it, I pass them as a dictionary of type [String:Any]. This is an example of it:
let signupQueryData : [String : Any] = [
"watermarks": [
"email" : correo_user as String,
"event_type" : "app" as String,
"watermark" : marcaAgua as String,
"date" : "\(dateActual) \(hour):\(minutes)" as String,
"location" : latitudYLongitud as String,
"segment" : 1 as Int,
"time" : "\(hour):\(minutes)" as String,
"country" : "\(qlq)" as String,
"city" : "Caracas" as String
]
]
And this is what it prints of parameters in the function marcaAgua:
["watermarks": ["time": "22:10", "segment": 1, "location": "location", "email": "mail", "event_type": "app", "watermark": "e356eaadcb3aa4a1049441fc48d83a22", "date": "13.07.2021 22:10", "country": "Venezuela", "city": "Caracas"]]
When I do that, I get the following error:
failure(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})
Try do like this
func marcaAgua(parameters: [String: Any],
completion: #escaping (Result<[MarcaAguaResData], Error>)-> Void) {
let urlString = baseUrl + "events"
guard let url = URL(string: urlString) else {
completion(.failure(NetworkingError.badUrl))
return
}
var request = URLRequest(url: url)
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
request.httpMethod = "POST"
request.setValue("Bearer \(token_login)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
guard let unwrappedResponse = response as? HTTPURLResponse else {
completion(.failure(NetworkingError.badResponse))
return
}
switch unwrappedResponse.statusCode {
case 200 ..< 300:
print("success")
default:
print("failure")
}
if let unwrappedError = error {
completion(.failure(unwrappedError))
return
}
if let unwrappedData = data {
do{
let json = try JSONSerialization.jsonObject(with: unwrappedData, options:.allowFragments)
if let successRes = try? JSONDecoder().decode([MarcaAguaResData].self, from: unwrappedData){
completion(.success(successRes))
}else{
let errorResponse = try JSONDecoder().decode([MarcaAguaErrorResponse].self, from: unwrappedData)
completion(.failure(errorResponse as! Error))
}
}catch{
completion(.failure(error))
}
}
}
}
task.resume()
}
initialise Variables
var invitationsArray = Array<[String: Any]>()
var invitations = Array<[String: Any]>()
Logic
invitations = [["friend_id": "\(each.friendId!)", "invited_type": "friend"]]
invitationsArray.append(contentsOf: invitations)
Set variables
let params: [String: Any] = [
"user_id":Global.shared.currentUserLogin.id,
"ride_name": planARide.name!,
"ride_description": planARide.description!,
"ride_type": planARide.rideType!,
"ride_date_and_time": planARide.rideDate!,
"ride_city": planARide.city!,
"ride_meeting_spot": planARide.rideMeetingSpot!,
"ride_meeting_latitude": planARide.latitude!,
"ride_meeting_longitude": planARide.longitude!,
"ride_intensity": planARide.rideIntensity!,
"time_length_of_ride": planARide.rideTime!,
"reoccuring_ride": planARide.rideReccurring!,
"special_instructions": planARide.specialInstruction!,
"open_ride_to_biking_community": planARide.openRideToBikingCommunity!,
"invitations": invitationsArray
]

How to Pass Key Value Parameter in JSON POST method in Swift?

This is API http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/
its parameter: "contactsList" : ["5987606147", "6179987671", "5082508888"]
its header: ["deviceid": "584D97F-761A-4C24-8C4B-C145A8B8BD75", "userType": "personal", "key": "9609cc826b0d472faf9967370c095c21"]
In my code if i put breakpoint then filtertaggedUser() is calling but i am unable to go inside completionHandler the access is not going inside dataTask
Access going to else part why? the api is working.
i am trying to pass parameter key value in URL string like below
let urlStr = "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/?contactsList=" + "8908908900"
is this correct approch?
code for above API:
func filtertaggedUser() {
print("inside filter taggedusers")
let headers = ["deviceid": "584D97F-761A-4C24-8C4B-C145A8B8BD75", "userType": "personal", "key": "9609cc826b0d472faf9967370c095c21"]
let urlStr = "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/?contactsList=" + "8908908900"
let request = NSMutableURLRequest(url: NSURL(string:urlStr)! as URL,cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
// access not coming here
let httpResponse = response as? HTTPURLResponse
if httpResponse!.statusCode == 200 {
print("filter taggedusers inside")
do {
print("filter taggedusers inside do")
let jsonObject = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! [String :AnyObject]
print("filter taggedusers \(jsonObject)")
} catch { print(error.localizedDescription) }
} else { Constants.showAlertView(alertViewTitle: "", Message: "Something went wrong, Please try again", on: self) }
})
dataTask.resume()
}
OUTPUT:
POSTMAN OUTPUT
POSTMAN Body
why response is not coming, where i did mistake, please help me with the code.
We can call the Post request API like below,
func getPostString(params:[String:Any]) -> String
{
var data = [String]()
for(key, value) in params
{
data.append(key + "=\(value)")
}
print(data.map { String($0) }.joined(separator: "&"))
return data.map { String($0) }.joined(separator: "&")
}
func callPostApi(){
let url = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
request.setValue("584D97F-761A-4C24-8C4B-C145A8B8BD75", forHTTPHeaderField: "deviceid")
request.setValue("9609cc826b0d472faf9967370c095c21", forHTTPHeaderField: "key")
request.setValue("personal", forHTTPHeaderField: "userType")
let parameters = getPostString(params: ["contactsList":["8908908900"]])
request.httpBody = parameters.data(using: .utf8)
// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
let httpResponse = response as? HTTPURLResponse
print(httpResponse!.statusCode)
// Check for Error
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string:\n \(dataString)")
}
}
task.resume()
}
Output :
{"8908908900":{"userId":"9609cc826b0d472faf9967370c095c21","userName":"Satish Madhavarapu","profilePic":null,"oniTaag":true,"tagged":false,"userType":"personal"}}

Not able to get success in api response

This is how I am making an api request using URLSession:
let url = URL(string: "http://192.168.1.21.2/FeatureRequestComponent/FeatureRequestComponentAPI")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let parameters: [String: Any] = [
"AppID": "67B10F42-A372-4D4B-B630-5933E3F7FD65",
"FeatureTitle": "ABCD",
"UserName": "Ayaz",
"UserEmail": self.userEmailTextfield.text ?? "",
"Priority":"H",
"Description": self.featureDescriptionTextView.text ?? "",
"UseCase": self.useCaseTextView.text ?? "",
"DeviceType" : "iPhone"
]
request.httpBody = parameters.percentEscaped().data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data,
let response = response as? HTTPURLResponse,
error == nil else { // check for fundamental networking error
print("error", error ?? "Unknown error")
return
}
guard (200 ... 299) ~= response.statusCode else { // check for http errors
print("statusCode should be 2xx, but is \(response.statusCode)")
print("response = \(response)")
return
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
}
extension Dictionary {
func percentEscaped() -> String {
return map { (key, value) in
let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
return escapedKey + "=" + escapedValue
}
.joined(separator: "&")
}
}
extension CharacterSet {
static let urlQueryValueAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]#" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return allowed
}()
}
above I have given the extensions for percent escaped and a character set also
But the response I get is an error like this:
responseString = Optional("{\"isError\":true,\"ErrorMessage\":\"Unknown Error Occured\",\"Result\":{},\"ErrorCode\":999}")
What am I doing wrong here...? I'm supposed to get a success in my response but what I'm getting is the error message.
I tried to detect the problem in your code but I did not find it
use my code war it works well
I hope this helps you
let jsonData = try? JSONSerialization.data(withJSONObject: ["username":username,"password":password])
var request = URLRequest(url: URL(string: "http://api.com/login")!)
request.httpMethod = "POST";
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let dataJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = dataJSON as? [String: Any] {
DispatchQueue.main.async {
let User = responseJSON["user"] as! [String:Any]
print("user: ", User)
print("name: ", User["name"]!)
print("email: ", User["email"]!)
}
}else {
print("error")
}
}
task.resume()

Receive data as NSArray serialize the object and use each value

I'm am trying to use the data of this request. I don't know how to receive data that comes in NSArray. So what I want to know is how can I use each one of the values that are in the array like "addresses" and "awards"?
(I'm using Swifty framework)
This is the server response and the data what I want to use. or better store it in a variable.
[
{
"addresses": [
{
"idAddress": 1,
"idProgram": 1,
"descriptionAddress": "Address1",
"registerDateAddress": "2017-09-12T11:03:53.083",
"isActive": true
}
],
"awards": [
{
"idAward": 1,
"idProgram": 1,
"nameAward": "Awards1",
"descriptionAward": "ImagenAward1",
"imageAward": "ImagenAward1.png",
"registerDateAward": "2017-09-12T11:03:57.67",
"isActive": true
}
]
And this is my code:
func getTheProgram(onSuccess: #escaping(JSON) -> Void, onFailure: #escaping(Error) -> Void) {
print("xxxxxxxxxx", userId ?? "")
guard let url = URL(string: "http://www.my_url.com") else {return}
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("xxxxxxxxx", forHTTPHeaderField: "Authorization")
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
if let response = response {
print("Response",response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! NSArray
print(json )
let result = JSON(data: data)
onSuccess(result)
print("xxxxxx")
} catch {
print(error)
print("xxxxxxx")
}
}
if(error != nil){
onFailure(error!)
print("xxxxxx")
} else{
}
})
task.resume()
}

Parsing strange JSON - swift

I am starting my adventure with Swift and iOS developing. And I am fighting for few hours with parsing this json result:
[
[
{
"id": 289462,
"value": "24.80",
"taken_at": "2017-07-02 19:03:03",
"key": "temperature"
}
],
[
{
"id": 289463,
"value": "52.20",
"taken_at": "2017-07-02 19:03:05",
"key": "humidity"
}
]
]
It hasn't got this "name" before all of results, and I don't know, maybe this is causing errors? And below is my function to get data:
func get_data()
{
let headers = [
"content-type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
"postman-token": "fd20c3c4-650e-743c-3066-597de91f3873"
]
let postData = NSMutableData(data: "auth_key=32fd26f62677e7aa56027d9c228e1e9d6d96abc5d10f547dcb66e2a2f6ed13".data(using: String.Encoding.utf8)!)
let request = NSMutableURLRequest(url: NSURL(string: "http://192.168.0.22/last")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
// print(error)
} else {
//let httpResponse = response as? HTTPURLResponse
var keys = [String]()
do {
if let data = data,
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let mes = json[""] as? [[String: Any]] {
for me in mes {
if let name = me["key"] as? String {
keys.append(name)
}
}
}
} catch {
print("Error deserializing JSON: \(error)")
}
print(keys)
}
})
dataTask.resume()
}
I've tried several codes from different sites which I googled and still array is remaining empty :(
You're right the JSON is strange, the root object is [[Any]]. You can get the key values with
if let json = try JSONSerialization.jsonObject(with: data) as? [[Any]] {
for item in json {
if let firstItem = item.first as? [String:Any], let key = firstItem["key"] as? String {
keys.append(key)
}
}
}
However if the JSON was in much more suitable format
[
{
"id": 289462,
"value": "24.80",
"taken_at": "2017-07-02 19:03:03",
"key": "temperature"
},
{
"id": 289463,
"value": "52.20",
"taken_at": "2017-07-02 19:03:05",
"key": "humidity"
}
]
you could reduce the code to
if let json = try JSONSerialization.jsonObject(with: data) as? [[String:Any]] {
keys = json.flatMap { $0["key"] as? String }
}

Resources