Receipt validation iOS - The file could not be opened because there is no such file - swift

I'm working on a subscription IAP. I set all purchases up, their details come back well, I can do the purchases in sandbox and get all the messages alright. The problem I have now is checking the receipt. I always get a URL returned alright, but when I try to read it I keep getting error that the file does not exist. So I try and refresh with SKReceiptRefreshRequest. Try again, still same.
I have uninstalled app on simulator and two real devices, try again from new install and same problem. One thing I realised, one of the real devices displays the password prompt request with [Sandbox] mention. However after two prompts (including accepting password), instead of purchase completed I get a "user/password don't match" message. On simulator when prompted for itunes account and password it all goes through but the actual purchase confirmation never comes (I waited 4 minutes, stable internet connection).
This is the validation process (I have changed it quite a few times, from different tutorials and other people's problems)
let receiptURL = Bundle.main.appStoreReceiptURL
func receiptValidation() {
print("1")
print("2", receiptURL)
do {
print("3")
let receiptData = try Data(contentsOf: receiptURL!, options: .alwaysMapped)
print(receiptData)
let receiptString = receiptData.base64EncodedString(options: [])
let dict = ["receipt-data" : receiptString, "password" : "\(password)"] as [String : Any]
do {
print("4")
let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
if let sandboxURL = Foundation.URL(string:"https://sandbox.itunes.apple.com/verifyReceipt") {
print("5")
var request = URLRequest(url: sandboxURL)
request.httpMethod = "POST"
request.httpBody = jsonData
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: request) { data, response, error in
print("6")
if let receivedData = data,
let httpResponse = response as? HTTPURLResponse,
error == nil,
httpResponse.statusCode == 200 {
print("7")
do {
print("8")
if let jsonResponse = try JSONSerialization.jsonObject(with: receivedData, options: JSONSerialization.ReadingOptions.mutableContainers) as? Dictionary<String, AnyObject> {
print(jsonResponse, jsonResponse.count)
// parse and verify the required informatin in the jsonResponse
} else { print("Failed to cast serialized JSON to Dictionary<String, AnyObject>") }
}
catch { print("Couldn't serialize JSON with error: " + error.localizedDescription) }
}
}
print("51")
task.resume()
} else { print("Couldn't convert string into URL. Check for special characters.") }
}
catch { print("Couldn't create JSON with error: " + error.localizedDescription) }
}
catch {
let appReceiptRefreshRequest = SKReceiptRefreshRequest(receiptProperties: nil)
appReceiptRefreshRequest.delegate = self
appReceiptRefreshRequest.start()
print("Couldn't read receipt data with error: " + error.localizedDescription) }
}
func requestDidFinish(_ request: SKRequest) {
print("???")
do {
let receipt = try Data(contentsOf: receiptURL!) //force unwrap is safe here, control can't land here if receiptURL is nil
print(receipt)
} catch {
print("WTF NO RECEIPT")
// still no receipt, possible but unlikely to occur since this is the "success" delegate method
}
}
And this is the Debugging output from running the app. receiptURL varies between simulator/real device, but other then that everything remains the same.
1
2 Optional(file:///Users/apple/Library/Developer/CoreSimulator/Devices/47EA3293-9B13-4808-BD0B-13D884D14BFE/data/Containers/Data/Application/2F1B7E4E-C523-4270-BF46-6D77F7A2220C/StoreKit/receipt)
3
Couldn't read receipt data with error: The file “receipt” couldn’t be opened because there is no such file.
???
WTF NO RECEIPT
???
WTF NO RECEIPT
Why can't I get the receipt created, or found? Is it a device problem, a bug or am I oblivious to something?

The whole IAP process works asynchronously due to which you will not receive the receipt data unless the whole process has been completed successfully. I can't see the whole code based on what you have pasted in your question above but if you are trying to access the receipt data immediately on the action of a button or something similar, you will not get it.
The correct way to access receipt data is to try accessing the receipt based on success completion handler callback of your IAP request. Once you submit the IAP request there is a server side process which takes care of processing the IAP and then a callback handler from IAP SKPaymentTransactionObserver class is triggered. Using the notification handler from this class you can send the update to your ViewController to check for receipt data.

While further researching, I have found the following article, which solved the problem
article
Important: If you mistakenly use a sandbox tester account to log in to a production environment on your test device instead of your test environment, the sandbox account becomes invalid and can’t be used again. If this happens, create a new sandbox tester account with a new email address.

Related

Alamofire Bad Network Connection | Swift

I would like to implement a way to check if the network is weak or disconnected during network calls I perform using Alamofire 4.9 - the following is what I am currently attempting to do, but I have noticed that if the network it off it never jumps to this line:
URLError.Code.notConnectedToInternet
why does this occur, is there a better way of attempting this?
//Fetch new data
guard let url = URL(string: "test.com")
else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = "value1=test1&value2=test2".data(using: .utf8)
URLSession.shared.dataTask(with: request) { [self] data, _, error in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
let res = try decoder.decode([Structure].self, from: data)
}
}
catch {
if let err = error as? URLError, err.code == URLError.Code.notConnectedToInternet {
// No internet
} else {
print(error)
}
}
}.resume()
There are a variety of errors that can be produced by poor or entirely broken connectivity. .notConnectedToInternet is simply one of them. There is no single, exhaustive list provided by Apple of which errors may be returned when there are connectivity issues, so you'll want to experiment and see what you can produce. Additionally, there are a variety of errors which you can probably throw into a "network connectivity" bucket, such as .dnsLookupFailed or .cannotConnectToHost. Ultimately it may not be worth it to differentiate different types of URLErrors.
By the way, you should use Alamofire 5 if you can, as Alamofire 4 is no longer supported.

API network request error on iOS device, not simulator

ok so i've been trying to get this problem figured out for 2 days now, hoping someone can help.
quick background, i’m making an api request for data. using a function that calls a service function i made. now everything works good on the first load, collectionview loads fine. at some point i run another call for more data. accept now i get a URL Error.
This doesn’t work on my iphone, but does work perfectly on simulator, so not sure what it could be.
heres the service function that makes the api request:
func fetchYoutubeData(interest: String, maxResult: Int, pageToken: String, completion: #escaping(Result<Youtube, WHError>) -> Void) {
let urlString = baseYoutubeURL+interest+youtubeAPIKey+"&maxResults=\(maxResult)&pageToken=\(pageToken)"
guard let url = URL(string: urlString) else {
completion(.failure(.URLError))
return
}
let session = URLSession.shared
let task = session.dataTask(with: url) { (data, _, error) in
if let _ = error {
completion(.failure(.DataError))
return
}
guard let data = data else { return }
do {
let result = try JSONDecoder().decode(Youtube.self, from: data)
print(result)
completion(.success(result))
} catch {
completion(.failure(.JSONError))
}
}
task.resume()
}
heres my controller function that calls service and handles the data on completion:
func fetchNewData(maxResult: Int, pageToken: String) {
guard let interest = self.interest.text else { return }
print(pageToken)
NetworkServices.shared.fetchYoutubeData(interest: interest, maxResult: maxResult, pageToken: pageToken) { [unowned self] (result) in
switch result {
case .success(let youtubeGroup):
let items = youtubeGroup.items
self.youtubeData.items.append(contentsOf: items)
DispatchQueue.main.async {
self.horizontalCollectionView.reloadData()
}
case .failure(let error):
print("DOES GET ERROR")
print(error)
}
}
}
again it works perfectly on simulator, but not on my device, i can get first call to work, but after that, once i use pageToken to get more data, i get a URL Error.
any help would be seriously appreciated
so of course like alot of things , it's something small I missed. I'll keep the question here, incase someone finds themself in a similar situation.
the problem was in the first request I reformat the "interest" to remove spaces from the string and replace them with +. you need to do this for the Youtube API query string that you provide.
i did this in the first request, but for my query for additional data, I forgot to reformat the request in the separate call.
easy fix thankfully
I added "App Transport Security Settings" to the Info.plist file then selected "Allow Arbitrary Loads" and set that value to "YES" and that worked. My assumption is that there was an issue with the security cert on the client development environment that was preventing the app from making calls over HTTPS.
And never fear, I only allow arbitrary loads in the dev and qa environments.

Swift, URLSession, viewDidLoad, tableViewController

I've never really gotten the nuances of async operations so time and again, I get stymied. And I just can't figure it out.
I'm trying to do some very simple web scraping.
My local volleyball association has a page (verbose HTML, not responsive, not mobile-friendly, yaddah, yaddah, yaddah) which shows the refs assigned to each game of the season. I'm trying to write a silly little app which will scrape that page (no API, no direct access to db, etc.) and display the data in a grouped table. The first group will show today's matches (time, home team, away team). The second group will show tomorrow's matches. Third group shows the entire season's matches.
Using code I found elsewhere, my viewDidLoad loads the page, scrapes the data and parses it into an array. Once I've parsed the data, I have three arrays: today, tomorrow, and matches, all are [Match].
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: urlString)!
let request = NSMutableURLRequest(url: url)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if let error = error {
print (error)
} else {
if let unwrappedData = data {
// scrape, scrape, parse, parse
matchRow = ...
self.matches.append(matchRow)
if matchRow.date == todaysDate {
self.today.append(matchRow)
} else if matchRow.date == tomorrowsDate {
self.tomorrow.append(matchRow)
}
}
}
}
task.resume()
}
As I'm sure is no surprise to anyone who understands async operations, my table is empty. I've checked and I see the the data is there and properly parsed, etc. But I can't for the life of me figure out how get the data in my table. The way I have it now, the data is not ready when numberOfSections or numberOfRowsInSection is called.
I've found the Ray Wenderlich tutorial on URLSession and I also have a Udemy course (Rob Percival) that builds an app to get the weather using web scraping, but in both those instances, the app starts and waits for user input before going out to the web to get the data. I want my app to get the data immediately upon launch, without user interaction. But I just can't figure out what changes I need to make so that those examples work with my program.
Help, please.
You can simply reload the tableviews once the data arrays are getting populated from the URLSession completion block. Have you tried that. Sample snippet may be like the one follows.
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if let error = error {
print (error)
} else {
if let unwrappedData = data {
// scrape, scrape, parse, parse
matchRow = ...
self.matches.append(matchRow)
if matchRow.date == todaysDate {
self.today.append(matchRow)
} else if matchRow.date == tomorrowsDate {
self.tomorrow.append(matchRow)
}
}
DispatchQueue.main.async { [weak self] in
self?.todayTableView.reloadData()
self?.tomorrowTableView.reloadData()
}
}
}

Swift program never enters CompletionHandler for a dataTask

I am in the process of implementing a REST API with Swift. Of course, part of this API is using HTTP requests to retrieve and send data.
Full disclosure, I am inexperienced with Swift and am using this as a learning project to get my feet wet, so to speak. But it's turned into much more of a difficult project than I anticipated.
In implementing the first get method, I have (finally) gotten rid of all the compilation errors. However, when I call the function which utilizes the URLRequest, URLSession, dataTask, etc, it is never entered.
Upon debugging the program, I can watch the program execution reach the CompletionHandler, and skip over it right to "task.resume()."
A similar construction works in a Swift Playground, but does not work in the actual project proper.
So far I have tried a few things, namely making the function access a class instance variable, in hopes that that would force it to execute. But it does not.
I think the issue may be dealing with synchronicity, and perhaps I need to use a Semaphore, but I want to make sure I'm not missing anything obvious first.
import Foundation
/**
A class to wrap all GET and POST requests, to avoid the necessity of repeatedly writing request code in each API method.
*/
class BasicRequest {
private var url: URL
private var header: [String: String]
private var responseType: String
private var jsonResponse: Any?
init(url: URL, header: [String: String], responseType: String) {
self.url = url
self.header = header
self.responseType = responseType
} //END INIT
public func requestJSON() -> Any {
// Create the URLRequest object, and fill the header with the header fields as provided.
var urlRequest = URLRequest(url: self.url)
for (value, key) in self.header {
urlRequest.addValue(value, forHTTPHeaderField: key)
}
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
print("Entered the completion handler")
if error != nil {
return
}
guard let httpResponse = response as? HTTPURLResponse, 200 == httpResponse.statusCode else {
print("HTTP Request unsuccessful")
return
}
guard let mime = response?.mimeType, mime == "application/json" else {
print("Not a JSON response")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
print(json)
self.jsonResponse = json
} catch {
print("Could not transform to JSON")
return
}
}
task.resume()
return "Function has returned"
} //END REQUESTJSON
}
The expected result would be returning a JSON object, however that does not seem to be the case.
With respect to error messages, I get none. The only log I get in the debugger is the boilerplate "process exited with code 0."
To be truthful, I'm at a loss with what is causing this not to work.
It appears you're writing this in a command-line app. In that case the program is terminating before the URLRequest completes.
I think the issue may be dealing with synchronicity, and perhaps I need to use a Semaphore, but I want to make sure I'm not missing anything obvious first.
Exactly.
The typical tool in Swift is DispatchGroup, which is just a higher-level kind of semaphore. Call dispatchGroup.enter() before starting the request, and all dispatchGroup.leave() at the end of the completion handler. In your calling code, include dispatchGroup.wait() to wait for it. (If that's not clear, I can add code for it, but there are also a lot of SO answers you can find that will demonstrate it.)

CloudKit Error: Change Token Expired, Reset Needed

Swift 3.1, Xcode 8.3.3
I keep getting an error from CloudKit and I don't know what to do about it.
I'm tracking notifications from CloudKit like this:
let operation = CKFetchNotificationChangesOperation(previousServerChangeToken: previousChangeToken)
//Hold the notification IDs we processed so we can tell CloudKit to never send them to us again
var notificationIDs = [CKNotificationID]()
operation.notificationChangedBlock = { [weak self] notification in
guard let notification = notification as? CKQueryNotification else { return }
if let id = notification.notificationID {
notificationIDs.append(id)
}
}
operation.fetchNotificationChangesCompletionBlock = { [weak self] newToken, error in
if let error = error{
print(error) //<-- <!> This is the error <!>
}else{
self?.previousChangeToken = newToken
//All records are in, now save the data locally
let fetchOperation = CKFetchRecordsOperation(recordIDs: recordIDs)
fetchOperation.fetchRecordsCompletionBlock = { [weak self] records, error in
if let e = error {
print("fetchRecordsCompletionBlock Error fetching: \(e)")
}
//Save records to local persistence...
}
self?.privateDB.add(fetchOperation)
//Tell CloudKit we've read the notifications
let operationRead = CKMarkNotificationsReadOperation(notificationIDsToMarkRead: notificationIDs)
self?.container.add(operationRead)
}
}
container.add(operation)
And the error says:
<CKError 0x174241e90: "Change Token Expired" (21/1016); server message
= "Error code: RESET_NEEDED"; uuid = ...; container ID = "...">
The CKServerChangeToken documentation don't mention anything about resetting the token, and the CloudKit dashboard doesn't offer any such option.
Any idea what I'm supposed to do?
This error code is CKErrorCodeChangeTokenExpired, and it's an indication that you need to re-sync your changes.
https://developer.apple.com/documentation/cloudkit/ckerror/2325216-changetokenexpired
This error code gets returned when the change token is too old, or the container has been reset (resetting the container invalidates old change tokens).
The comments related to this error code include:
(Describing the code itself):
The previousServerChangeToken value is too old and the client must re-sync from scratch
(On various fetch operation completion/updated blocks):
If the server returns a CKErrorChangeTokenExpired error, the serverChangeToken used for this record zone when initting this operation was too old and the client should toss its local cache and re-fetch the changes in this record zone starting with a nil serverChangeToken.