Why my return is nil but if i press the url in chrome/safari, i can get data?
The text you try to get is probably not UTF-8, try with another encoding, like this for example:
let myString = NSString(data: data, encoding: NSASCIIStringEncoding)
Update: read Martin R's answer for how to find the right encoding.
iOS NSURL returning nil on valid URL
The problem is that you need to percent-encode your values in the URL string. When it’s received by the server, it will decode this percent-encoded string in the URL into the desired value.
But rather than percent-encoding yourself, you can use NSURLComponents
. For example, if you want a
to have the value of @"1\\tb"
, you can do:
NSURLComponents *components = [NSURLComponents componentsWithString:@"http://localhost:8080"];
components.queryItems = @[
[NSURLQueryItem queryItemWithName:@"a" value:@"1\\tb"],
[NSURLQueryItem queryItemWithName:@"b" value:@"2"]
];
NSURL *url = components.URL;
Yielding:
http://localhost:8080?a=1%5Ctb&b=2
Or, if you wanted it to have the tab character in the value associated with a
(i.e. %09
):
NSURLComponents *components = [NSURLComponents componentsWithString:@"http://localhost:8080"];
components.queryItems = @[
[NSURLQueryItem queryItemWithName:@"a" value:@"1\tb"],
[NSURLQueryItem queryItemWithName:@"b" value:@"2"]
];
NSURL *url = components.URL;
Yielding:
http://localhost:8080?a=1%09b&b=2
It just depends upon whether your server is expecting two characters, the \
followed by t
(the first example) or the single \t
character (the second example). Either way, the respective use of NSURLComponents
will take care of the percent-encoding for you, and your server will decode it.
For what it’s worth, the one caveat is the +
character, which NSURLComponents
won’t percent-encode for you (because, technically, a +
character is allowed in a URL query). The problem is that the +
character is interpreted as a space character by most web servers (per the x-www-form-urlencoded
spec). If you need to pass a literal +
character, you might want to replace those +
characters, as advised by Apple:
NSURLComponents *components = [NSURLComponents componentsWithString:@"http://localhost:8080"];
components.queryItems = @[
[NSURLQueryItem queryItemWithName:@"q" value:@"Romeo+Juliet"]
];
components.percentEncodedQuery = [components.percentEncodedQuery stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
NSURL *url = components.URL;
NSString encoding returns nil on url content
The problem there as already mentioned by rmaddy it is the encoding you are using. You need to use NSASCIIStringEncoding
.
if let url = URL(string: "https://www.google.com") {
URLSession.shared.dataTask(with: url) {
data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let data = data, error == nil,
let urlContent = String(data: data, encoding: .ascii)
else { return }
print(urlContent)
}.resume()
}
Or taking a clue from Martin R you can detect the string encoding from the response:
extension String {
var textEncodingToStringEncoding: Encoding {
return Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(self as CFString)))
}
}
if let url = URL(string: "https://www.google.com") {
URLSession.shared.dataTask(with: url) {
data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let data = data, error == nil,
let textEncoding = response?.textEncodingName,
let urlContent = String(data: data, encoding: textEncoding.textEncodingToStringEncoding)
else { return }
print(urlContent)
}.resume()
}
NSURLSession does not returns data for http/https
This is a text encoding problem. The webpage at http://www.google.com/finance/converter?a=1&from=USD&to=INR is not encoded with UTF-8
but with ISO-8859-1
.
In this case, you have to use NSISOLatin1StringEncoding
instead of NSUTF8StringEncoding
for NSString:
let webcontent = NSString(data: url_content, encoding: NSISOLatin1StringEncoding)
XCode swift HTTPS: String(data: data!, encoding: NSUTF8StringEncoding ) return nil
in my code usually make a fall back:
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
if (strData == nil){
//roll back to ASCII ...
strData = NSString(data: data, encoding: NSASCIIStringEncoding)
}
xcode NSURLConnection post return 200 but NSData always null?
Status code 200 shows that you have now active and successful connection with the server. But that does not mean that you will get data successfully. There are some points needs to be take care:
Your request should match
Content-Type
required on server. If it is not match you will not receive data or invalid dataMake sure which method you have called
GET
orPOST
.Some web-services are also required specific
user-agent
, So if it required check for user-agent alsoParameter values: Even if you get success code - The datatype values required to server some time mis lead to you. Most common possible datatype mis match are
bool
,int
andfloat
. It is essential to check that you have pass exact datatype value. e.g. 1 is consider asint
and also as abool
value.Encoding Scheme: You must have to parse receive data with exactly same encoding scheme as per server specification.
Edit:
In your case you just need to change encoding:NSASCIIStringEncoding
.
-(void) connection:(NSURLConnection *)connection didReceiveData: (NSData *) incomingData
{
NSLog(@"data---%@",[[NSString alloc] initWithData: incomingData encoding:NSASCIIStringEncoding]);
}
Replace above method with your code.
Swift get HTML from URL
It seems that www.google.com sends the response using the
ISO 8859-1 encoding, the corresponding NSString
encoding is NSISOLatin1StringEncoding
:
html = try NSString(contentsOfURL: testUrl!, encoding: NSISOLatin1StringEncoding)
You can also detect the HTTP response encoding automatically,
see for example https://stackoverflow.com/a/32051684/1187415.
Related Topics
How to Create Usdz File Using Xcode Converter
Swift - Resolving a Math Operation in a String
Getting a "This Application Is Modifying the Autolayout Engine from a Background Thread" Error
How Does String.Index Work in Swift
How to Save and Read Array of Array in Nsuserdefaults in Swift
Passing an Array to a Function With Variable Number of Args in Swift
Formatting Input For Currency With Nsnumberformatter in Swift
How to Get the Current Date in Short Format in Swift
What Does an Exclamation Mark Mean in the Swift Language
Nsobject Subclass in Swift: Hash VS Hashvalue, Isequal VS ==
Difference Between a Weak Reference and an Unowned Reference
Swiftui: How to Make Textfield Become First Responder