let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
if error != nil {
println("error=\(error)")
return
}
In this code I'm getting an error for dataTaskWithRequest(request) for with my PHP connection. It worked before migrating to Swift 2.
Here is correct syntax:
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {(data, response, error) in
// your code
})
Sample code from this answer:
var url : NSURL = NSURL(string: "https://itunes.apple.com/search?term=\(searchTerm)&media=software")
var request: NSURLRequest = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
// notice that I can omit the types of data, response and error
// your code
});
// do whatever you need with the task
UPDATE:
let url : NSURL = NSURL(string: "https://itunes.apple.com/search?term=&media=software")!
let request: NSURLRequest = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions(rawValue: 0))
guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
print("Not a Dictionary")
//get your JSONData here from dictionary.
return
}
print("JSONDictionary! \(JSONDictionary)")
}
catch let JSONError as NSError {
print("\(JSONError)")
}
})
Related
Hello I'm trying to convert a short URL like https://goo.gl/maps/MoaZNS825rpixfKu5 to its original URL https://www.google.com/maps/place/WhirlyBall+Twin+Cities/#44.8508658,-93.2389179,17z/data=!3m1!4b1!4m5!3m4!1s0x87f62f7bd688277b:0xc0ec9f7b1ccd0da8!8m2!3d44.8510743!4d-93.2366811?hl=en-US
I found some solutions in similar old posts but they are not working with Xcode 12.4
I tried using the below code but it didn't return any value when I try to print expandedURL
let shortURL = "https://goo.gl/maps/MoaZNS825rpixfKu5"
func performRequest(urlString: String){
let urlString = shortURL
let url = URL(string: urlString)!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "HEAD"
URLSession.shared.dataTask(with: urlRequest) { (data, urlResponse, error) in
let expandedURL = urlResponse?.url?.absoluteString
print("expandedURL HEAD: \(expandedURL ?? "Oops, not URL")")
}
.resume()
}
I managed to get it to work with the below code
I know it's somehow a primitive way but it just worked with me :)
let shortURL = //"https://goo.gl/maps/MoaZNS825rpixfKu5"
"https://goo.gl/maps/xNdKp1Q1KqFeWQv99"
performRequest (urlString: shortURL)
func performRequest(urlString: String){
if let url = URL(string: urlString){
let session = URLSession(configuration: .default)
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "HEAD"
let task = session.dataTask(with: urlRequest, completionHandler: handle(data:response:error:))
task.resume()
}
}
func handle (data: Data?, response: URLResponse?, error: Error?){
if error != nil {
print (error)
return
}
if let safeData = data {
let dataString = String(data: safeData, encoding: .utf8)
let expandedURL = response?.url?.absoluteString
print(expandedURL!)
}
}
In using swift 2.2, while using NSURLSession I am not getting the Response. What am I doing wrong?
I have to pass parameters and header in POST request.
func API() {
let userName:String! = "uname"
let password:String! = "password"
let request = NSMutableURLRequest(URL: NSURL(string: URL)!)
request.HTTPMethod = "POST"
let data = try! NSJSONSerialization.dataWithJSONObject(parameter, options:[])
let json = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
request.HTTPBody = json.dataUsingEncoding(NSUTF8StringEncoding)
request.allHTTPHeaderFields = ["key":"value"]
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}
Result is:
responseString = Optional("")
Did you call this service on any REST client like Postman ? if yes and get response so try replace this line
request.allHTTPHeaderFields = ["key":"value"]
with this
request.setValue("value",forHTTPHeaderField:"Key")
and set all values
This question already has answers here:
Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)
(14 answers)
Closed 6 years ago.
I have a swift 2.3 project I just updated to swift 3.0 and the following code broke.
let task = URLSession.shared.dataTask(with: request, completionHandler: {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8)
print("responseString = \(responseString)")
})
task.resume()
I am unaware how to fix it
You can get that error if the request is a NSURLRequest rather than a URLRequest.
let url = URL(string: urlString)!
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
Or, if you're mutating the URLRequest, use var:
let url = URL(string: urlString)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = ...
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
Also, note, I've replaced NSString with String.
I am trying to do 2 HTTP requests
in the first request i will get a var that will be used in the second request.
My problem is when I do it using the code below it just runs the second request without running the first.
let url = NSURL(string:"https://loginurl")
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"
let contentType = " application/x-www-form-urlencoded"
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
var dataString = "user details"
var requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
NSURLProtocol.setProperty(requestBodyData!.length, forKey: "Content-Length", inRequest: request)
var response: NSURLResponse?
let session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
//code for getting the session id to be used in the second request
})
task.resume()
let url2 = NSURL(string:"http://url2?sessionid")
let request2 = NSMutableURLRequest(URL: url2!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request2.HTTPMethod = "GET"
dataString=""
requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request2.HTTPBody = requestBodyData
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request2)
task = session.dataTaskWithRequest(request2, completionHandler: {data, response, error -> Void in
})
task.resume()
Can anybody explain what can be wrong with this code
Problem 2:
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let httpRes = response as? NSHTTPURLResponse {
let html = NSString(data:data!, encoding:NSUTF8StringEncoding)
if let match = html?.rangeOfString("(?<=sessionid=')[^\';]+", options: .RegularExpressionSearch) {
portalid = (html?.substringWithRange(match))!
}
}
When I run in simulator it works without issues but when I debug it on iPhone it crashes showing this error "Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString substringWithRange:]: Range {9223372036854775807, 0} out of bounds; string length 52427'"
Thanks
Here is code sample which makes two requests:
//: Playground - noun: a place where people can play
import UIKit
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
let session = NSURLSession.sharedSession()
session.dataTaskWithURL(NSURL(string: "http://www.google.com")!, completionHandler: { (data :NSData?, response :NSURLResponse?, error :NSError?) -> Void in
let res = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(res!)
// make a new request here
let innerSession = NSURLSession.sharedSession()
innerSession.dataTaskWithURL(NSURL(string: "http://www.google.com")!, completionHandler: { (data :NSData?, response :NSURLResponse?, error :NSError?) -> Void in
let res = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(res!)
}).resume()
}).resume()
I am trying to create an HTTP request and return some JSON data. It is connecting to the API correctly and returning data but when I run the app it is returning the line I printed ("Error") without continuing through the application. If I remove the println and continue through the breakpoints the app just runs forever with me being unable to continue through the breakpoints.
I'm sure I have some fundamental misunderstanding of how closures are supposed to work. What am I missing here?
func logIn() {
var url = "https://www.photoshelter.com/psapi/v3/mem/authenticate?api_key=(api_key)&email=(email)&password=(password)&mode=token"
var baseURL:NSURL? = NSURL(string: url)
var request: NSMutableURLRequest? = NSMutableURLRequest(URL: baseURL!)
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request!, completionHandler: { (data, response, error) -> Void in
println("Error")
var responseObject = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
})
task.resume()
}
#IBAction func signInButton(sender: AnyObject) {
logIn()
}
This or a close variation is how I do nearly all of my networking. It looks like your implementation isn't actually doing anything.
func logIn() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let url = NSURL(string: "https://www.photoshelter.com/psapi/v3/mem/authenticate?api_key=(api_key)&email=(email)&password=(password)&mode=token")
let session = NSURLSession.sharedSession()
// Request
let request = NSMutableURLRequest(URL: url!)
// You can set request properties like HTTPMethod and HTTPBody to customize things
let loginUserDataTask = session.dataTaskWithRequest(request, completionHandler: { data, response, error in
var success = false
if let error = error {
println("Failure! \(error)")
if error.code == -999 { return }
} else if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
if let array = parseJSON(data) {
success = true
// Do something with array
}
} else {
println("Failure! \(response)")
}
}
dispatch_async(dispatch_get_main_queue()) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
})
loginUserDataTask?.resume()
}
and here is parseJSON: to handle the data:
func parseJSON(data: NSData) -> [AnyObject]? {
var error: NSError?
if let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error) as? [AnyObject] {
return json
} else if let error = error {
println("JSON Error: \(error)")
} else {
println("Unknown JSON Error")
}
return nil
}