Unable to read data while making request - ios

here i am getting strange issue like i can able to make request into simulator but in real device gave error like "unable to read data" also attached screen shot
My Code :
let urlPath: String = url_to_request
let url:NSURL = NSURL(string: urlPath)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

Related

How to refresh UIWebView images

I went through a few SO post and can't seem to fix my issues.
The codes works fine, but if i update my profile pics, the UIWebView, will still show the cached image instead of the updated image.
if i close my app and reopen, the webview will update to the new image.
any pointer are greatly appreciated.
func getLeaderBoard()
{
leaderWebView.loadRequest(getStaticWebView(urlStr: getLeaderBoardUrl) as URLRequest)
}
func getStaticWebView(urlStr:String) -> NSMutableURLRequest
{
let url = URL.init(string: urlStr)
let request = NSMutableURLRequest.init(url: url!)
request.httpMethod = "GET"
request.setValue("token \(kToken)", forHTTPHeaderField: "Authorization")
request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
URLCache.shared.removeAllCachedResponses()
URLCache.shared.diskCapacity = 0
URLCache.shared.memoryCapacity = 0
return request
}

sendAsynchronousRequest was deprecated in iOS 9 (Swift 2) - Transfer Code?

I'm using XCode 7.3. Here is my code:
func postToServerFunction() {
let url: NSURL = NSURL(string: "http://mytesturl.com")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
//let textfeld = String(UserTextField.text)
let bodyData = "data=" + UserTextField.text!
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in}}
This works fine and my php-Script gets the string it should. But there is the
sendAsynchronousRequest was deprecated in iOS 9
message.
As I read, with Swift 2 the method has changed.
I searched a lot for this error, but I'm not able to convert the code that it matches to Swift 2. As I also read, i should use something like this
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request)
but I can't get it down. And actually, I don't understand every single line. I wrote the code myself, but from some examples that it works for me.
This is the most basic way you'd use a shared session:
if let url = NSURL(string: "http://mytesturl.com"),
userField = UserTextField.text {
let request = NSMutableURLRequest(URL: url)
let bodyData = "data=" + userField
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request,completionHandler: {(data,response,error) in
}
)
dataTask.resume()
}
For more detail on the other approaches including background and ephemeral sessions, as well as how to handle the NUSRLResponse, see my blogpost.
As you've found out NSURLConnection has been deprecated and NSURLSession is the new shiny.
For your example to work you still need to use the NSURL and the NSURLRequest that you have already created, and then you need an NSURLSession which you can use in various ways.
I can see that you already use the callback so in your case I assume it would be
session.dataTaskWithRequest(request) { (data, response, error) in
//magic goes here
}
and then the important thing to remember is to call resume() on your task.
So...to translate your code I'm thinking something along those lines
func postToServerFunction() {
let url: NSURL = NSURL(string: "http://mytesturl.com")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
//let textfeld = String(UserTextField.text)
let bodyData = "data=" + UserTextField.text!
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
let session = NSURLSession.defaultSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) in
//magic goes here
}
task.resume()
}
You can read more about NSURL session in this tutorial from raywenderlich.com
Hope that helps

Why URLs from NSUserDefaults and CoreData don't allow to send POST request?

I need help, 'cause I've run into following problem and don't know about any reasons of it.
If I declare my POST request like this:
let urlString = url.valueForKey("url") as? String
let myUrl = NSURL(string: urlString!);
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let postString = "imei=AA022F8E-9E20-482D-80CB-DE06A8CD0990&pin=1234";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
or like this:
requestURL = NSKeyedUnarchiver.unarchiveObjectWithData(savedPeople) as! String
let myUrl = NSURL(string: requestURL!);
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST"
let postString = "imei=AA022F8E-9E20-482D-80CB-DE06A8CD0990&pin=1234";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
it will looks like I sending empty POST request.
But if I do it in common way, like this:
let myUrl = NSURL(string: "http://www.wtek.ru/test.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let postString = "imei=AA022F8E-9E20-482D-80CB-DE06A8CD0990&pin=1234";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
it will work correctly.
Also, first two version work correctly when I send request to http://127.0.0.1/request.php, but it doesn't work when I try to send my request outside of local network.
Where can be the problem?
The problem was not in Core Data / NSUserDefaults.
It happened because I've put to Core Data link without www.
So, if you faced with same problem, please, double-check it.

How to make CONNECT call in iOS?

NSURLSession supports POST and GET; does it also support CONNECT?
If so, what is the exact syntax?
Thanks!
Use NSMutableURLRequest to set whatever HTTP method you want
let session = NSURLSession()
guard let url = NSURL(string: "http://www.google.com") else {
fatalError("Error creating NSURL for http://www.google.com")
}
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "CONNECT"
let task = session.dataTaskWithRequest(request)
task.resume()

NSURLRequest produce different result than HTTP proxy client

I send the same HTTP message from a HTTP proxy client and with NSURLRequest + NSURLConnection, and get back different result. It is an authentication request. From HTTP proxy authentication request is accepted, sending from app not. Why? Accepted means after redirection HTML will contains no Oops substring.
let url = NSURL(string: "http://www.swisshttp.weact.ch/en/user/login")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let email2 = (viewController!.email.text as NSString).stringByReplacingOccurrencesOfString("#", withString: "%40")
let str = "name=\(email2)&pass=\(viewController!.password.text)&form_id=user_login" as NSString
let d = str.dataUsingEncoding(NSUTF8StringEncoding)
if let d2 = d {
request.HTTPBody = d2
let urlConnection = NSURLConnection(request: request, delegate: self)
}
UPDATE
I have put #teamnorge's code below into playground and into an empty Single View Application project. Returned HTML in project contains the Oops substring, code used in playground not containes it, any idea what is going on, why same request produce different HTML result? I get failed message also from iOS device and from simulator too.
UPDATE
Removed NSURLRequest cache like here recommended, but still not works as expected. And here.
UPDATE
Tried to remove all the credentials like here, but didn't help, no credential was found.
It looks like when you receive HTTP 302 and new Location URL, iOS does automatically fetch the page by this URL, so I guess your response is in fact the HTML content of the redirection page. Please verify.
UPDATE:
import UIKit
import XCPlayground
let url = NSURL(string: "http://www.swisshttp.weact.ch/en/user/login")
let request = NSMutableURLRequest(URL: url!)
let str = "name=kukodajanos%40icloud.com&pass=jelszo&form_id=user_login" as NSString
let d = str.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = d
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.currentQueue()) { response, maybeData, error in
if let data = maybeData {
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
println(contents)
if contents!.rangeOfString("Oops").length == 0 {
println("success")
} else {
println("failed")
}
} else {
println(error.localizedDescription)
}
}
XCPSetExecutionShouldContinueIndefinitely()

Resources