How can I get source code from URL with SSL using Swift? - ios

I am trying to read a source code of a site from its URL.
Below is my code.
let myURLString = "https://theUrlOfTheSite"
let myURL = NSURL(string: myURLString)
var error: NSError?
let myHTMLString = String(contentsOfURL: myURL!, encoding: NSUTF8StringEncoding, error: &error)
if let error = error {
println("Error : \(error)")
} else {
println(myHTMLString)
}
It works for some site, but not for others. I get the following error
2014-12-21 19:11:54.032 MyPlayground[2912:345862] NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9807)
Error : Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)"
I think it's because the site is https, not http. (I don't really know about this stuff but..SSL something??)
So my question is, what should I do to make my code work??
I searched for hours but I'm new to iOS and Swift, so no progress.
Do I have to make NSURLConnection or something? Because all I want to do is get the source code. Must be a simple job I guess..
Any help will be appreciated. Thanks in advance.

Related

"The file “command.cgi” couldn’t be opened."

FlashAir W-04 Fourth Generation SD memory card
In my iOS app directory listing api not working.
Response :
Task .<0> HTTP load failed (error code: -1003 [12:8])
2019-05-21 23:32:40.267572+0530 Razzo[10489:87069] NSURLConnection finished with error - code -1003
Error Domain=NSCocoaErrorDomain Code=256 "The file “command.cgi” couldn’t be opened." UserInfo={NSURL=http://flashair/command.cgi?op=100&DIR=/DCIM}
Please help me what was wrong
below code snippet
private func getdata() {
let url100 = URL(string: "http://flashair/command.cgi?op=100&DIR=/DCIM")
var dirStr: String? = nil
do {
if let url100 = url100 {
dirStr = try String(contentsOf: url100, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
if let dir = dirStr {
arrayfiles = dir.components(separatedBy: "\n")
}
tblContent.reloadData()
}
} catch {
print(error)
self.displayAlert(message: error.localizedDescription)
}
}
Config file below
[Vendor]
CIPATH=/DCIM/100__TSB/FA000001.JPG
APPMODE=4
APPNETWORKKEY=12345678
VERSION=F15DBW3BW4.00.03
CID=02544d535733324755e3c6dc7b012301
PRODUCT=FlashAir
VENDOR=TOSHIBA
MASTERCODE=f437b71e0e4f
LOCK=1
contentsOf: url100 would be for a local file URL. You are not providing a valid file URL.
If your file is remote you need to download the file as data with URLSession. If it is local you need to work out its file URL.

TIC SSL Trust Error while accessing data from https url

I have tried to access data from a https url by following.
DispatchQueue.global(qos: .background).async {
let stringURL = "https://192.168.104.91:8443/update_info.xml"
let url = URL(string: stringURL)
var data:Data? = nil
do {
data = try Data(contentsOf: url!)
} catch {
print(error.localizedDescription)
}
}
But i am getting following error.
2018-03-21 12:49:35.529949+0600 AppName[704:205346] TIC SSL Trust Error [1:0x1c0171a00]: 3:0
2018-03-21 12:49:35.541223+0600 AppName[704:205346] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
2018-03-21 12:49:35.541283+0600 AppName[704:205346] Task <7D4A1063-B946-4588-830A-CE73AF5B4995>.<0> HTTP load failed (error code: -1202 [3:-9813])
2018-03-21 12:49:35.541771+0600 AppName[704:205344] NSURLConnection finished with error - code -1202
The file “update_info.xml” couldn’t be opened.
Any suggestions ?

Data task with URL timed out

I am trying to access a website. I am using a dataTaskWithURL request.
Here is my code:
let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in
print("2")
if let urlContent = data {
print("3")
let stringContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding)!
let arr = stringContent.componentsSeparatedByString("<b>The computer's solutions will appear below</b><br>")
let second = arr[1]
let newArr = second.componentsSeparatedByString("</tr></table></center><p align=\"center\">")
let results = newArr[0]
self.resultsLabel.text = results
self.stopActivity()
} else {
print(error)
self.stopActivity()
}
})
task.resume()
I have also tried running this code on the main block:
dispatch_async(dispatch_get_main_queue(), {() -> Void in
// Code
})
However, neither of these has been successful. I repeatedly get the following error
Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x7ff0a3f4c6e0 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=THE URL I AM TRYING TO ACCESS, NSErrorFailingURLKey=THE URL I AM TRYING TO ACCESS, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.})
I have tried looking at this post and this one as well. However, I have not been successful with them. The website loads fairly quickly. How do I get rid of this error?
It could be caused by a number of things; If the issue is happening in the Simulator, I suggest restarting it as per the suggestions in the SO posts below:
Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."
Error: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."
NSURLErrorDomain Code=-1001 error when a http post request is sent
Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit
How to use NSURLSessionDataTask in Swift
It might be help to print response as well to see if the HTTP headers can provide a clue.
I realized that I was using https:// instead of http://.

Corruption of contentsURL encoding type?

I am still struggling with accessing certain Google pages and have tried multiple combinations of encoding types. I've also tried UTF8 and then falling through to a default if that fails. This is where things get very odd.
I do the following:
println("URL within process page = \(url)")
println("Trying NSUTF8")
origURLString = String(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: &error)
if (error != nil) {
println("Error = \(error)")
println("Trying NSASCII next")
origURLString = String(contentsOfURL: url, encoding: NSASCIIStringEncoding, error: &error)
if (error != nil) {
println("Error = \(error)")
}
}
if (error != nil) {
return "There seems to be a problem going to this site"
}
Both calls to contentsOfURL fail with the following trace:
Trying NSUTF8
Error = Optional(Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)" UserInfo=0x7fbbda599b00 {NSURL=http://www.google.com/search?ie=ISO-8859-1&hl=en-GB&source=hp&q=hello&btnG=Google+Search&gbv=1, NSStringEncoding=4})
Trying NSASCII next
Error = Optional(Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)" UserInfo=0x7fbbda599b00 {NSURL=http://www.google.com/search?ie=ISO-8859-1&hl=en-GB&source=hp&q=hello&btnG=Google+Search&gbv=1, NSStringEncoding=4})
However, if I don't try using NSUTF8StringEncoding and just use ASCII encoding:
origURLString = String(contentsOfURL: url, encoding: NSASCIIStringEncoding, error: &error)
Then this works (not so well since the encoding isn't right). No error code at least, and I get a full HTML page.
Obviously, I can't use ASCII encoding for everything and I would rather build a general approach that checks UFT8 first before defaulting to something else.
Am I corrupting something with my first approach? Is the error message carrying over?
I tried testing every NSEncodingType in a loop and that failed, so I narrowed it down to just two and I get the same issue.
Ideas? I'm at a complete loss.
This function helps me correct my text strings:
func utf(txt:String)->NSString{
var newtxt = txt.stringByReplacingOccurrencesOfString("\\n", withString: " ", options: NSStringCompareOptions.LiteralSearch, range: nil)
if var scb = NSString(CString: newtxt ,encoding:NSNonLossyASCIIStringEncoding){
return scb
}else{
var scb = NSString(CString:newtxt, encoding:NSUTF8StringEncoding)
return scb!
}
}
This is interesting because it occupies the encoding that fits
according to the text string to be sent.

plist attachment from email in swift (NS Cocoa Error Domain Code 260)

I am sending some ios file data via an email contained in a plist. No issues attaching it, I can check the file and the contents. It's all there and I can open it as a plist. Clicking on it (I have associated it with my app) it opens and I get a valid path:
file:///private/var/mobile/Containers/Data/Application/C5454580-2BEB-4515-9BDE-FED85FF54F76/Documents/Inbox/ShareStrength-11.bps
that I pass but when I try and read back the NSDictionary (plist) I get nil content.
let sourceFile = NSDictionary(contentsOfFile: URLString)
Any ideas on what is going wrong. Having difficulty debugging.
EDIT: I found some error code:
var error: NSError?
let content = NSString(contentsOfFile: URLString, encoding:NSUTF8StringEncoding, error: &error)
if content != nil
{
println("content: \(content)")
}
else
{
println("error: \(error)")
}
And I get the error:
error: Optional(Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x17eceeb0 {NSFilePath=file:///private/var/mobile/Containers/Data/Application/571DB0FF-6C5A-4BEB-9FA8-6E4DFE10E850/Documents/Inbox/ShareStrength-13.bps, NSUnderlyingError=0x17ee9810 "The operation couldn’t be completed. No such file or directory"})
Is this a sandbox issue? How can I copy the attachment being passed as a URL?
I was using:
let URLString: String = url.absoluteString!
instead of:
let URLString: String = url.path!
Hope this helps someone else

Resources