I have a url session requesting data by URL. The issue is the data retrieved by the url on a fresh app open is not proper.
Problem:
For example I delete the app and re-download the app and make a request by URL (1st time):
Status Code: 200
Bytes: 6365 bytes
no metadata
The second time I make the url request:
- Status Code: 200
- Bytes: 1044440 bytes
- Metadata is valid and retreived
Example url:
Description:
The only time I have this issue is when I delete the app and make this request the first time. After the first request all other request are fine and work as normal using the same function.
This issue only happens when I delete that app to test as a first time user.
import Foundation
import Kanna
import WebKit
public extension URL {
struct ValidationQueue {
static var queue = OperationQueue()
}
func fetchPageInfo(_ completion: @escaping ((_ title: String?, _ description: String?, _ previewImage: String?) -> Void), failure: @escaping ((_ errorMessage: String) -> Void)) {
var request = URLRequest(url: self)
let newUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"
request.setValue(newUserAgent, forHTTPHeaderField: "User-Agent")
URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
DispatchQueue.main.async(execute: {
// print(error)
failure("Url receive no response")
})
return
}
if let urlResponse = response as? HTTPURLResponse {
if urlResponse.statusCode >= 200 && urlResponse.statusCode < 400 {
print("Satus code: \(urlResponse.statusCode)")
if let data = data {
print("data: \(data)")
if let doc = try? Kanna.HTML(html: data, encoding: String.Encoding.utf8) {
let title = doc.title
var description: String? = nil
var previewImage: String? = nil
if let nodes = doc.head?.xpath("//meta").enumerated() {
print("nodes: \(nodes)")
for node in nodes {
if node.element["property"]?.contains("description") == true ||
node.element["name"] == "description" {
description = node.element["content"]
}
if node.element["property"]?.contains("image") == true &&
node.element["content"]?.contains("http") == true {
previewImage = node.element["content"]
}
}
}
DispatchQueue.main.async(execute: {
print("t: \(title) \n d: \(description) \n i: \(previewImage)")
completion(title, description, previewImage)
})
}
}
} else {
DispatchQueue.main.async(execute: {
failure("Url received \(urlResponse.statusCode) response")
})
return
}
}
}.resume()
}
}