How to get the KeyValue from QueryString and return string in specific string format - swift3

I am a newbie and need help.
I need to create a baseString from the below QueryString.
This baseString will look something like this in the end:
&ap=裕廊坊 心邻坊&oq=c# nunit mac&q=c# nunit mac
QueryString :
HTTPS://www.sky.com/api/v1/rest/level2/in-in/?q=c%23+nunit+mac&oq=c%23+nunit+mac&ap=裕坊%20邻坊
Problem:
How to get the KeyValue from the above QueryString
1) By getting all the components separated by "&" like below
--Keyvalue from the Query String:
q=c%23+nunit+mac&oq
oq=c%23+nunit+mac
ap=裕坊%20邻坊
I would use struct as I need to call the static func:
struct BaseString {
static func createBaseString(authPrefix,signMethod,urlPath,nonce, timestamp,delimeter="&", bool sort= true, bool quote = false) -> String? {
var dict = [String:String]()
let url = NSURL(string: urlPath)
var keyValues = url.query?.componentsSeparatedByString("&")
//-(1)- adding keyValue into Dictinary
dict.??
//-- how to add the data below?
//- after (1) : Add other key value into same Dictionary
dict Add(authPrefix + "_timestamp", timestamp);
dict.Add(authPrefix + "_nonce", nonce);
dict.Add(authPrefix + "_signature_method", signMethod);
dict.Add(authPrefix + "_version", "1.0");
var return_format:String
if quote == true{
//-- create a baseString
sort the Dictionary
return_format = "&" + url + "&" +Dictionary.ToString()
(format: String = "q ="V1" " the value with double quote)
}else{
//-- create a baseString
sort the Dictionary
return_format = Dictionary.ToString()
(format:Strig = " q=v2")
}
var baseString = return_format
return baseString
}
}
Thanks. your help is much appreciated.

You can get Key-Value dictionary from your URL's query items with the help of URLQueryItem class, like this
let urlString = "https://www.sky.com/api/v1/rest/level2/in-in/?q=c%23+nunit+mac&oq=c%23+nunit+mac&ap=裕坊%20邻坊"
let encodedUrlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let items = URLComponents(string: encodedUrlString)?.queryItems
var keyValues: [String: String] = [:]
items?.forEach{
item in
keyValues[item.name] = item.value
}
print(keyValues)
//["q": "c%23+nunit+mac", "ap": "裕坊%20邻坊", "oq": "c%23+nunit+mac"]
Hope this will help you.
If you need to obtain Query substring from your url string, you need to create URL from it and get query.
guard let url = URL(string: encodedUrlString) else {
fatalError()
}
let queryString = url.query!
print(queryString.removingPercentEncoding)
//q=c%23+nunit+mac&oq=c%23+nunit+mac&ap=裕坊%20邻坊
If you need to add new components to your query,
var components = URLComponents(string: encodedUrlString)
let item = URLQueryItem(name: "NEWVKEY", value: "NEWVALUE")
components?.queryItems?.append(item)
let url = components?.url
let resultString = url?.absoluteString
//or
let resultString2 = url?.absoluteString.removingPercentEncoding
The idea is to use URL processing abilities of Swift standard library. Please check the documentation of URL, URLComponents, URLQueryItem structs. Don't write string processing code, manipulate URLs instead.
https://developer.apple.com/documentation/foundation/url
https://developer.apple.com/documentation/foundation/urlcomponents
https://developer.apple.com/documentation/foundation/urlqueryitem

Related

SharePoint WebsInfo Description is always Null

I'm trying to get the Description of a Site but it's always null in WebsInfo! Can someone please help me understand this? I also tried using OpenWeb but that was messing up the URL that I passed in.
var site = new SPSite(currentWeb.Url);
string url = currentWeb.Url + #"/" + siteName;
var webObject = site.AllWebs;
foreach (var web in webObject.WebsInfo)
{
siteDescription = web.Description;
}
I guess there is a bug in the WebsInfo that has never been resolved!! I ended up using SPWebCollection.
//This will find the current URL and iterate through it's site Collection
var oSiteCollection = new SPSite(SPContext.Current.Web.Url);
//Gets all webs meaning sub webs and their webs.
var collWebsites = oSiteCollection.AllWebs;
foreach (SPWeb web in collWebsites)
{
if (web.ServerRelativeUrl.StartsWith(kpi.BusinessUnitUrl))
{
kpi.BusinessUnitDescription = web.Description;
kpi.SiteSpecificAreaDescription = web.Description;
var collLists = web.Lists;
IterateLists(collLists, false, ref kpi);
}
}

Can't get key value as String from metadata

I'm grabbing metadata from an MPMediaItem like this:
let url = item.value(forProperty:MPMediaItemPropertyAssetURL) as? NSURL
let asset = AVURLAsset(url: url! as URL, options: nil)
let metaArray = asset.metadata
for metadata in metaArray{
print("-----metadata:\(metadata)")
print("-----metadata.key:\(String(describing: metadata.key))")
}
However, when I get a block of metadata printed the "key" is printed as a numeric value instead of "pcst" as shown in the printout:
-----metadata:<AVMetadataItem: 0x1740153f0, identifier=itsk/pcst, keySpace=itsk, key class = __NSCFNumber, key=pcst, commonKey=(null), extendedLanguageTag=(null), dataType=com.apple.metadata.datatype.int8, time={INVALID}, duration={INVALID}, startDate=(null), extras={
dataLength = 1;
dataType = 21;
dataTypeNamespace = "com.apple.itunes";
}, value=1>
-----metadata.key:Optional(1885565812)
This is happening for all of the metadata/keys (there are 29 in this particular media item).
Also note that this line of code:
let realString = NSString(string: metadata.key! as! String)
causes this error:
Could not cast value of type '__NSCFNumber' (0x1b80dcdf0) to 'NSString' (0x1b80edae8).
How can I get the string value for the key ("pcst") ?
May be what you are looking for is identifier property of AVMetadataItem.
for metadata in metaArray{
print(metadata.identifier ?? "DefaultValue")
}
In case others want to see the code I'm using:
func returnKeyString(_ inVal: String)->String{
// expecting the metadata for "identifier" as input - returns key value
// eg "itsk/ldes" -> "ldes"
// or "id3/%00WFD" etc. -> "wfd"
var sFinal:String = ""
if (inVal.contains("/")){
sFinal = (inVal.components(separatedBy: "/")[1])
}
if sFinal.contains("%"){
sFinal = sFinal.components(separatedBy: "%")[1]
let index1 = sFinal.index(sFinal.startIndex, offsetBy: 2)
sFinal = sFinal.substring(from: index1)
}
return sFinal.lowercased()
}

findText find something containing a quote

I have a script that takes the current document and looks for a user defined string using findText. If that string contains a quote (like: Bob's Burgers). findText does not find it. I know it uses regular expressions, but I cannot figure out how to format the expression so it finds this properly.
code example:
var target = "Bob's Burgers";
var body = DocumentApp.getActiveDocument().getBody();
try
{
var searchResult = body.findText(target);
//does not find the text. But can find Bob easily.
}
catch(e) { ...}
I tried the findText method using the code from this post:
function highlightText(findMe) {
var body = DocumentApp.getActiveDocument().getBody();
var foundElement = body.findText(findMe);
while (foundElement != null) {
// Get the text object from the element
var foundText = foundElement.getElement().asText();
// Where in the Element is the found text?
var start = foundElement.getStartOffset();
var end = foundElement.getEndOffsetInclusive();
// Change the background color to yellow
foundText.setBackgroundColor(start, end, "#FCFC00");
// Find the next match
foundElement = body.findText(findMe, foundElement);
}
}
function myFunction() {
highlightText("Bob’s Burger");
}
Result:
Hope this helps.
Use \` instead of ` to escape it.
var target = "Bob\'s Burgers";

Swift: Finding an Object Property via regex

Target: The following function shall iterate over an array of objects and check a specific property of all objects. This property is a string and shall be matched with a user input via regex. If there's a match the object shall be added to an array which will further be passed to another function.
Problem: I don't know how to set up regex in Swift 3. I'm rather new in Swift at all, so an easily understandable solution would be very helpful :)
How it currently looks like:
func searchItems() -> [Item] {
var matches: [Item] = []
if let input = readLine() {
for item in Storage.storage.items { //items is a list of objects
if let query = //regex with query and item.name goes here {
matches.append(item)
}
}
return matches
} else {
print("Please type in what you're looking for.")
return searchItems()
}
}
This is what Item looks like (snippet):
class Item: CustomStringConvertible {
var name: String = ""
var amount: Int = 0
var price: Float = 0.00
var tags: [String] = []
var description: String {
if self.amount > 0 {
return "\(self.name) (\(self.amount) pcs. in storage) - \(price) €"
} else {
return "\(self.name) (SOLD OUT!!!) - \(price) €"
}
}
init(name: String, price: Float, amount: Int = 0) {
self.name = name
self.price = price
self.amount = amount
}
}
extension Item: Equatable {
static func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.name == rhs.name
}
}
Solved. I just edited this post to get a badge :D
For the purpose of letting the answer to be generic and clear, I will assume that the Item model is:
struct Item {
var email = ""
}
Consider that the output should be a filtered array of items that contains items with only valid email.
For such a functionality, you should use NSRegularExpression:
The NSRegularExpression class is used to represent and apply regular
expressions to Unicode strings. An instance of this class is an
immutable representation of a compiled regular expression pattern and
various option flags.
According to the following function:
func isMatches(_ regex: String, _ string: String) -> Bool {
do {
let regex = try NSRegularExpression(pattern: regex)
let matches = regex.matches(in: string, range: NSRange(location: 0, length: string.characters.count))
return matches.count != 0
} catch {
print("Something went wrong! Error: \(error.localizedDescription)")
}
return false
}
You can decide if the given string does matches the given regex.
Back to the example, consider that you have the following array of Item Model:
let items = [Item(email: "invalid email"),
Item(email: "email#email.com"),
Item(email: "Hello!"),
Item(email: "example#example.net")]
You can get the filtered array by using filter(_:) method:
Returns an array containing, in order, the elements of the sequence
that satisfy the given predicate.
as follows:
let emailRegex = "[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailItems = items.filter {
isMatches(emailRegex, $0.email)
}
print(emailItems) // [Item(email: "email#email.com"), Item(email: "example#example.net")]
Hope this helped.
You can do the same with filter function
let matches = Storage.storage.items.filter({ $0.yourStringPropertyHere == input })

Scala - replaceAllIn

First off, I'm new to Scala.
I'm trying to make a template parser in Scala (similar to Smarty (PHP)). It needs to search through the document, replacing anything inside "{{ }}" tags, with anything provided in the HashMap.
I'm currently stuck here:
import scala.collection.mutable.HashMap
import scala.io.Source
class Template(filename: String, vars: HashMap[Symbol, Any]) {
def parse() = {
var contents = Source.fromFile(filename, "ASCII").mkString
var rule = """\{\{(.*)\}\}""".r
//for(rule(v) <- rule findAllIn contents) {
// yield v
//}
//rule.replaceAllIn(contents, )
}
}
var t = new Template("FILENAME", new HashMap[Symbol, Any])
println(t.parse)
The part's that I've commented are things that I've thought about doing.
Thanks
I've come a little further...
import scala.collection.mutable.HashMap
import scala.io.Source
import java.util.regex.Pattern
import java.util.regex.Matcher
class Template(filename: String, vars: HashMap[Symbol, Any]) {
def findAndReplace(m: Matcher)(callback: String => String):String = {
val sb = new StringBuffer
while (m.find) {
m.appendReplacement(sb, callback(m.group(1)))
}
m.appendTail(sb)
sb.toString
}
def parse() = {
var contents = Source.fromFile(filename, "ASCII").mkString
val m = Pattern.compile("""\{\{(.*)\}\}""").matcher(contents)
findAndReplace(m){ x => x }
}
}
var t = new Template("FILENAME.html", new HashMap[Symbol, Any])
println(t.parse)
At the moment it just currently adds whatever was inside of the tag, back into the document. I'm wondering if there is an easier way of doing a find-and-replace style regexp in Scala?
I'd do it like this (String as key instead of Symbol):
var s : String = input // line, whatever
val regexp = """pattern""".r
while(regexp findFirstIn s != None) {
s = regexp replaceFirstIn (s, vars(regexp.findFirstIn(s).get))
}
If you prefer not using var, go recursive instead of using while. And, of course, a stringbuilder would be more efficient. In that case, I might do the following:
val regexp = """^(.*?)(?:{{(pattern)}})?""".r
for(subs <- regexp findAllIn s)
subs match {
case regexp(prefix, var) => sb.append(prefix); if (var != null) sb.append("{{"+vars(var)+"}}")
case _ => error("Shouldn't happen")
}
That way you keep appending the non-changing part, followed by the next part to be replaced.
There is a flavor of replaceAllIn in util.matching.Regex that accepts a replacer callback. A short example:
import util.matching.Regex
def replaceVars(r: Regex)(getVar: String => String) = {
def replacement(m: Regex.Match) = {
import java.util.regex.Matcher
require(m.groupCount == 1)
Matcher.quoteReplacement( getVar(m group 1) )
}
(s: String) => r.replaceAllIn(s, replacement _)
}
This is how we would use it:
val r = """\{\{([^{}]+)\}\}""".r
val m = Map("FILENAME" -> "aaa.txt",
"ENCODING" -> "UTF-8")
val template = replaceVars(r)( m.withDefaultValue("UNKNOWN") )
println( template("""whatever input contains {{FILENAME}} and
unknown key {{NOVAL}} and {{FILENAME}} again,
and {{ENCODING}}""") )
Note Matcher.quoteReplacement escapes $ characters in the replacement string. Otherwise you may get java.lang.IllegalArgumentException: Illegal group reference, replaceAll and dollar signs. See the blog post on why this may happen.
Here is also interesting way how to do the same using functions compose:
val Regexp = """\{\{([^{}]+)\}\}""".r
val map = Map("VARIABLE1" -> "VALUE1", "VARIABLE2" -> "VALUE2", "VARIABLE3" -> "VALUE3")
val incomingData = "I'm {{VARIABLE1}}. I'm {{VARIABLE2}}. And I'm {{VARIABLE3}}. And also {{VARIABLE1}}"
def replace(incoming: String) = {
def replace(what: String, `with`: String)(where: String) = where.replace(what, `with`)
val composedReplace = Regexp.findAllMatchIn(incoming).map { m => replace(m.matched, map(m.group(1)))(_) }.reduceLeftOption((lf, rf) => lf compose rf).getOrElse(identity[String](_))
composedReplace(incomingData)
}
println(replace(incomingData))
//OUTPUT: I'm VALUE1. I'm VALUE2. And I'm VALUE3. And also VALUE1