NSURL "missing argument for parameter in call" Swift - ios

I use obj-c and swift classes together. And at one swift class, I try to convert objective c code to swift. However, I have a problem about NSURL.
the original code is:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#://", appItem.URLSchema]];
and URLSchema is declared in the header file like this:
#property (nonatomic, copy) NSString *URLSchema;
I convert the objective c code which is above to swift:
var url: NSURL = NSURL(string:"%#://",relativeToURL: appItem.URLSchema)
but it says "missing argument for parameter "path" in call"
when I try this:
var url: NSURL = NSURL.URLWithString("%#://", appItem.URLSchema)
it says extra argument in call.
what do you suggest to convert it properly?

The second argument : RelativeToURL has the type NSURL and you pass a String
Try this :
var url:NSURL = NSURL(string: "\(appItem.URLSchema)://")
For more informations, you can take a look on the 'String Interpolation' section in the "Swift programming langage" iBook.
String interpolation is a way to construct a new String value from a
mix of constants, variables, literals, and expressions by including
their values inside a string literal. Each item that you insert into
the string literal is wrapped in a pair of parentheses, prefixed by a
backslash

Related

Cannot invoke initializer for type 'URL' with no arguments - Swift 3

Receive error:
Cannot invoke initializer for type 'URL' with no arguments
Following is the code -
var databasePath = URL()
I have declare this variable globally. Also tried for
var databasePath: URL!
if let url = NSURL().absoluteURL { //error 1- Consecutive declarations on a line must be separated by ';'
databasePath = url //error2 - Variable used within its own initial value
}
Receive above 2 errors if write above code as replacement of var databasePath = URL() .
I am beginner in Swift. Please let me know the solution.
The URL initializer must have an argument.
Basically there are two types:
An URL in the file system
let databaseURL = URL(fileURLWithPath:"/path/to/file.ext")
An URL with an explicit scheme (e.g. http, ftp etc)
let databaseURL = URL(string:"http://myserver/path/to/file.ext")!
If the URL is guaranteed to be valid it can be unwrapped (!) otherwise use optical bindings (if let)
Swift- 5 Easy way
var fileDownloadedURL = URL(string: "")
Declare url in this way
var url: URL = NSURL() as URL

Can not create NSURL object because of "|" symbol in url string

I need to create an object of NSURL from url string like this. It contains | symbol. The problem is that NSURL constructor always returns nil, because of | symbol. How can I create this object?
I think it is lowercase l, not the pipe | character.
However, you can use stringByAddingPercentEncodingWithAllowedCharacters: with NSCharacterSet.URLQue‌​ryAllowedCharacterSet() to escape invalid characters in the URL:
url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQue‌​ryAllowedCharacterSet())
--
let url = "https://static-maps.yandex.ru/1.x/?l=map&pt=55,1583062965,61,3948104504,pm2rdm&size=600,300"
let escapedURL = url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQue‌​ryAllowedCharacterSet())
print(NSURL(string: escapedURL))

How to encode URL string such that it encodes & and spaces [duplicate]

I've got to send a https GET request to a web service in my iPhone app which is developing in Swift 1.2.
I am trying to construct query string parameters but got to encode them before send to server.
All good but not working when password contains '&' charcter. Expect to encode '&' character to '%26' but NOT working...
Just done a test when having '%'. Works as expected with '%' providing '%25'. But NOT convert '&' sign....
Tried following ways:
var testPassword1: String = "mypassword&1"
var testPassword2: String = "mypassword%1"
// Try to encode 'testPassword1'
testPassword1.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
testPassword1.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
// Try to encode 'testPassword2'
testPassword2.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
testPassword2.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
I've done the above tests and following are the response
Would like to know the correct way to do this. Thanks.
You should use NSURLComponents for your task.
Given a URL string, create a url-components:
let urlString = "http://example.com"
let urlComponents = NSURLComponents(string: urlString)!
Given a query parameter container (possibly a dictionary, or an array of (String, String?) tuple), create an array of NSURLQueryItems:
let queryParameters: [String: String?] = ["param": "az09-._~!$&'()*+,;=:#/?", "reserved": ":/?#[]#!$&'()*+,;="]
var queryItems = queryParameters.map { NSURLQueryItem(name: $0.0, value: $0.1) }
Append the query-component to the url-components:
urlComponents.queryItems = queryItems.count > 0 ? queryItems : nil
print(urlComponents.string!)
prints:
http://example.com?reserved=:/?%23%5B%5D#!$%26'()*+,;%3D&param=az09-._~!$%26'()*+,;%3D:#/?
I used such an utility method to URL-encode values in GET-requests:
#interface NSString (Ext)
#property (nonatomic, readonly) NSString *urlEncoded;
#end
#implementation NSString (Ext)
- (NSString *)urlEncoded {
NSMutableCharacterSet *const allowedCharacterSet = [NSCharacterSet URLQueryAllowedCharacterSet].mutableCopy;
// See https://en.wikipedia.org/wiki/Percent-encoding
[allowedCharacterSet removeCharactersInString:#"!*'();:#&=+$,/?#[]"]; // RFC 3986 section 2.2 Reserved Characters (January 2005)
NSString *const urlEncoded = [self stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
return urlEncoded;
}
#end
If you need to encode the & character, you can use the following:
var testPassword1: String = "mypassword&1"
testPassword1.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
testPassword1.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet(charactersInString: "&").invertedSet)!

Issue with converting NSString * to String and passing Character as parameter in Swift iOS

I am calling a Objective method from Swift by using a Bridging header.
-(NSString *) PatternSetCreator: (char)Signature detection_time_in_sec:(int)detection_time_in_sec patternLength:(int)patternLength maxPatternSetSize:(int)maxPatternSetSize
There are two issuse:
a) I am not able to pass a single character as parameter while calling this method from Swift
b) I am not exactly sure how to get the return type NSString and assign it to a String variable
A single C char in Swift is represented as CChar, a typealias for Int8.
(similarly, C int in Swift is CInt, a typealias for Int32)
If you want a specific character and are using Swift 1.2, there’s an initializer for UInt8 that takes a UnicodeScalar. Annoyingly, though, you have to then convert it to a Int8 to make it compatible with the C method:
let ch = CChar(UInt8(ascii: "x"))
let i = CInt(100)
let s = obj.PatternSetCreator(ch,
detection_time_in_sec: i,
patternLength: i,
maxPatternSetSize: i)
You should not need to do anything special to turn the returned NSString to a String. The bridging will do that automatically.
(or rather, it’ll return a String! – but if the objective c code is guaranteed to return a valid string every time and never a null pointer, the definition can be changed to -(nonnull NSString *) PatternSetCreator: etc… which means it will return a String instead)

How to bridge Swift String to Objective C NSString?

Am I taking crazy pills? Directly out of the documentation:
“Swift automatically bridges between the String type and the NSString class. This means that anywhere you use an NSString object, you can use a Swift String type instead and gain the benefits of both types—the String type’s interpolation and Swift-designed APIs and the NSString class’s broad functionality. For this reason, you should almost never need to use the NSString class directly in your own code. In fact, when Swift imports Objective-C APIs, it replaces all of the NSString types with String types. When your Objective-C code uses a Swift class, the importer replaces all of the String types with NSString in imported API.
To enable string bridging, just import Foundation.”
I've done this... consider:
import Foundation
var str = "Hello World"
var range = str.rangeOfString("e")
// returns error: String does not contain member named: rangeOfString()
However:
var str = "Hello World" as NSString
var range = str.rangeOfString("e")
// returns correct (2, 1)
Am I missing something?
To go from String to NSString use the following constructor:
let swiftString:String = "I'm a string."
let objCString:NSString = NSString(string:swiftString)
With Xcode 7 (beta), using a downcast from String to NSString, as in below example, will result in a warning message, Cast from 'String?' to unrelated type 'NSString' always fails:
let objcString:NSString = swiftString as! NSString // results in error
You already have the answer in your question. You're missing the cast. When writing Swift code, a statement such as this one
var str = "Hello World"
creates a Swift String, not an NSString. To make it work as an NSString, you should cast it to an NSString using the as operator before using it.
This is different than calling a method written in Objective-C and supplying a String instead of an NSString as a parameter.
Here is example for this :
string str_simple = "HELLO WORLD";
//string to NSString
NSString *stringinObjC = [NSString stringWithCString:str_simple.c_str()
encoding:[NSString defaultCStringEncoding]];
NSLog(stringinObjC);

Resources