How to integrate Odoo lead creation api in ios app? - ios

I am developing an application which is in swift and the backend is Odoo. Odoo apis calling is working fine using Alamofire. I have one issue with lead creation api. There is a format for product_id which is: [(6,0,[123,234])]. Here this format is not working if I pass it as a String and it is not accepted without as a string in JSON.
So can anyone tell me which type of format it is and how to pass it in post data?
Here is my code:
with Disctionary
let ids = selectedProducts.value(forKey: kId) as! NSArray
let productIds = NSMutableArray(capacity: 0)
productIds.add("[(6,0")
productIds.add("["+ids.componentsJoined(by: ",")+"])]")
saveDic[kProductId] = productIds.componentsJoined(by: ",")
with string:
let ids = selectedProducts.value(forKey: kId) as! NSArray
let productIds = NSMutableArray(capacity: 0)
productIds.add("[(6,0")
productIds.add("(6,0,["+ids.componentsJoined(by: ",")+"])")
let pid = "(6,0,["+ids.componentsJoined(by: ",")+"])"
postData += ", \"" + kProductId + "\" : [" + pid + "]"
Thank you

Related

How to separate two URLs in a String in Swift?

What is the best way to split this String into two using Swift?
"https://apod.nasa.gov/apod/http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif"
I only need the second part of url in the String. In this example, in this case I just need:
"http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif"
let str = "https://apod.nasa.gov/apod/http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif"
if let lastStr = str.components(separatedBy: "http").last
{
let result = "http" + lastStr
print(result)
}
Console Output: http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif

Syntax to put a variable in a string in swift3

A question I think pretty simple but I never had to do it in swift. it's pretty simple PHP but here I do not find my solution on the internet.
ask: I would like to add a variable in this chain of character. Instead of 123, I would need a variable.
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_123.json"
result = final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_VARAIBLE.json"
Can you give me the syntax in swift3 or direct me to a good tutorial.
You can create a string using string formatting.
String(format:"https://ozsqiqjf.preview.infomaniak.website/empdata_%d.json", variable)
let variable = 123
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(variable).json"
\(variable) is what you need
OR
use string formatting
let variable = 123
final let urlString = String(format:"https://ozsqiqjf.preview.infomaniak.website/empdata_%d.json", variable)
There is good documentation about Strings in Swift Language Guide. Your options are:
Concatenating Strings
let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_" + value + ".json"
String interpolation
let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(value).json"
Swift4 You can add a string in these ways:
var myString = "123" // Or VARAIBLE Here any string you pass!!
var urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(myString).json"
A simple way of doing it could be:
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_" + variablename + ".json"
You can also do it like this (a little more typesafe):
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(variablename).json"
Swift will read \(variablename) into the string automatically and accepts - among all things - integers.
let variable = 123
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_" + variable + ".json"
or
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(variable).json"

The '#' char gets converted to %23 causing the GET Request to fail

I am a new Swift developer using Swift 3 developing an iOS app. I need to make a URL Request to get some data from the web. That URL contains a # character.
I use URLComponents with URLQueryItems to build the request URL. During this process the # char gets converted to %23 which I think is valid utf8 encoding. Unfortunately, this causes the GET to fail.
To test I pasted the URL into my browser and changed %23 back to # and it worked just fine.
How can I fix this so it does not change # to URL. I did find a post from a couple years ago but it was using old framework items so it does not apply to me.
Below is the playground I made to illustrate and test this.
// ------------------------------------------------------------------
//: Playground - TestBuildURLWithParameters
//
// I am using this playground to build the proper
// URL for the GET request to get the detailed
// rtesults for a specific athlete where the "Key"
// is their Bib Nbr. If the GET cant find the specific
// Atlete with that URL it redirects you to the list
// of athlete results (which is no go to me in this case)
//
// Currently, there is a big "gotcha". In building the URL
// using component and query items, the foundation classes
// replace the '#' sign in the URL with the %23 which represents
// the pound sign. Unfortunately, the causes the GET to fail
// and redirects to athlete list which is not helpful
// I am still trying to figure out how to FORCE it to keep
// the '#" character in the URL so it will work
//
// ------------------------------------------------------------------
import Foundation
import UIKit
let baseURLString = "http://www.ironman.com/triathlon/events/americas/ironman-70.3/augusta/results.aspx"
let rd = "20150927"
let race = "augusta70.3"
let bibID = "93"
var detail = "1#axzz4FGGcjBOn"
print("Detail w/o unicocde: \(detail)")
detail = "1\u{0023}axzz4FGGcjBOn"
print("Detail with unicocde: \(detail)")
var components = URLComponents(string: baseURLString)!
var queryItems: [URLQueryItem] = [] // All Items after the "?"
let baseParams =
[
"rd": rd,
"race": race,
"bidID": bibID, // Note: HTML mispelled bib with bid so "bidID" is the URL search
"detail": detail
]
for (key, value) in baseParams
{
let item = URLQueryItem(name: key, value: value)
queryItems.append(item)
}
components.queryItems = queryItems // what does this look like
print("components: \(components)") // see it
It is not a good way to include fragment part of URL into query items.
Try this:
import Foundation
let baseURLString = "http://www.ironman.com/triathlon/events/americas/ironman-70.3/augusta/results.aspx"
let rd = "20150927"
let race = "augusta70.3"
let bibID = "93"
var detail = "1"
//# split the last query item and the fragment
let fragment = "axzz4FGGcjBOn"
var components = URLComponents(string: baseURLString)!
var queryItems: [URLQueryItem] = []
let baseParams =
[
"rd": rd,
"race": race,
"bidID": bibID,
"detail": detail
]
for (key, value) in baseParams
{
let item = URLQueryItem(name: key, value: value)
queryItems.append(item)
}
components.queryItems = queryItems
components.fragment = fragment
print("components: \(components)")
If you need you can choose the character that will receive the encoding.
In the charactersIn: you put all characters you want to encode.
Then you use the .inverted so all the others characters will go normal like this:
let customAllowedSet = NSCharacterSet(charactersIn:"=\"%/<>?#\\^`{|}").inverted
let encondedString = originalString.addingPercentEncoding(withAllowedCharacters: customAllowedSet)
print("enconded string: \(encondedString)")
Encode your parameters and then add it to URL, this will encode # before hitting API and you'll get desired result.
To encode parameters, you can use below code.
var parameterString = "your parameter string"
var encodedString = parameterString .addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
print(encodedString !)
I did get an answer via email from a friend that works for now. Basically, I added the query items manually to the URL using the URL extension below so it didn't monkey with the '#' char:
extension URL {
func appendingNonEscapedQueryItems(_ queryItems: [URLQueryItem]) -> URL {
let url = self
var urlString = url.absoluteString
for queryItem in queryItems {
let queryName = queryItem.name
guard let queryValue = queryItem.value else {
continue
}
let query = queryName + "=" + queryValue
if queryItem == queryItems.first {
urlString = urlString + "?" + query
}
else
{
urlString = urlString + "&" + query
}
}
return URL(string: urlString)!
}
}
...
let requestURL = components.url!.appendingNonEscapedQueryItems(queryItems)
print("URL \(requestURL)")

iOS String format

I have the following issue in swift
I have a String
let GET_LISTING = "Listing/GetDetails?deviceid=%#&listingid=%d";
the I use this line to get it formatted
let url = SERVER_URL + String.localizedStringWithFormat(GET_LISTING, deviceId, listingId);
when the number < 1000 it works fine
for example
Listing/GetDetails?deviceid=AB11F1D0-153E-48C3-950F-CC773BBCC683&listingid=500
if number > 1000 it is wrong
Listing/GetDetails?deviceid=AB11F1D0-153E-48C3-950F-CC773BBCC683&listingid=1,050
how can I solve this problem ?
You could convert the listingId to a String:
let GET_LISTING = "Listing/GetDetails?deviceid=%#&listingid=%#"
let url = SERVER_URL + String.localizedStringWithFormat(GET_LISTING, deviceId, String(listingId))

How to get time pattern using regex in a parsed xml variable in swift 2

I have a rss feed which I parse it's data using SWXMLHash, there are three type of data which I need from this feeds,Image src , title , time.
I don't have any problem with getting images and title but there is a bit problem in getting time value.
my rss feed time formate is like :
<item>
<title>item subject</title>
<description>
<img align="right" hspace="5" src="http://test.org/index/uploads/conductor/thumbnails/0192.jpg"/>
</description>
<pubDate>2015-11-14 05:05:03</pubDate>
</item>
problem is that pubDate tag contains date + time , but I need just the time.
is there a way to find xxxx-xx-xx pattern and replace it with ''
Or find xx:xx:xx which is time?
this is how I parse my rss feed :
struct sprog {
var spTitle : String!
var spImg : String!
var spTime : String!
}
var tableData = [sprog]()
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://razavitv.aqr.ir/index/conductor_module/rss")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
let processedString = (dataString as NSString).stringByReplacingOccurrencesOfString("<![CDATA[", withString: "").stringByReplacingOccurrencesOfString("]]>", withString: "") as String
let data: NSData = processedString.dataUsingEncoding(NSUTF8StringEncoding)!
let xml = SWXMLHash.parse(data)
//one root element
let count = xml["rss"]["channel"]["item"].all.count
for var i = 0; i < count; i++ {
let appName = xml["rss"]["channel"]["item"][i]["title"].element!.text!
let appUrl = xml["rss"]["channel"]["item"][i]["description"]["img"].element!.attributes["src"]
let appTime = xml["rss"]["channel"]["item"][i]["pubDate"].element!.text!
let ap = sprog(spTitle: appName , spImg : appUrl , spTime : appTime)
self.tableData.append(ap)
//for reducing delay of loading table view data
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
return
})
}
}
task.resume()
}
Don't use regex to turn a string into a date — date/time formatting and calculation is a much hairier problem than it ever appears. What time zone are you dealing with? What time zone is the user in? Is it a leap year? Is the date you're reading valid, even if it is/isn't a leap year? And that's all assuming you're dealing with a fixed format coming from the RSS feed... it gets even more fun when you're dealing with date strings that could come out of end-user-configured software.
Instead of trying to tackle that yourself, let the system do it for you. Use a date formatter to read the date (see "Parsing Fixed Format Date Representations" on that page for an example. Then, if you don't need parts of the date (like the day/month/year), create an NSDateComponents object from the date and read from it only the fields (hour/minute/etc) you're interested in.
Why Don't you use split ? your can split your variable and store time and date in different variables :
//seperate string by space
var apptime_array = appTime.componentsSeparatedByString(" ")
//seperate string by :
apptime_array = apptime_array[1].componentsSeparatedByString(":")
appTime = "\(apptime_array[0]):\(apptime_array[1])"

Resources