Code error in Tic-Tac-Toe game - ios

I would really appreciate your help with the following. I have been battling this small nuisance for a while now but without luck. I have this bit of code thats basically simulates a AI playing TIC TAC TOE against a player.
let Result = RowCheck(value: 0)
if Result != nil {
println("Computer has two in a row")
var WhereToPlayResult = WhereToPlay(Result.location, pattern: Result.pattern)
if !IsOccupied(WhereToPlayResult) {
SetImageForSpot(WhereToPlayResult, player: 0)
aiDeciding = false
CheckForWin()
return
}
return
}
RowCheck just checks for a pattern to play against.
func RowCheck(#‎value:Int) -> (location:String,pattern:String)? {
var AcceptableFinds = ["011","110","101"]
var FindFuncs = [CheckTop,CheckBottom,CheckLeft,CheckRight,CheckMiddleAcross,CheckMiddleDown,CheckDiagionalRightLeft,CheckDiagionalLeftRight]
for Algorthm in FindFuncs {
var AlgorthmResults = Algorthm(value:value)
if (find(AcceptableFinds,AlgorthmResults.pattern) != nil) {
return AlgorthmResults
}
}
return nil
}
But it gives me an error at:
var WhereToPlayResult = WhereToPlay(Result.location, pattern: Result.pattern)

Because your RowCheck method returns an optional (and might return nil), you need to either unwrap your optional or use a different assignment:
let Result = RowCheck(value: 0)
if Result != nil {
var WhereToPlayResult = WhereToPlay(Result!.location, pattern: Result!.pattern)
// ... ^ ^
}
if let Result = RowCheck(value: 0) {
// ...
}
Side note: only classes should be named starting with a capital letter. To stay within Apple's code style, you should variables and functions as result, rowCheck, etc.

Related

Cannot convert value of type 'inout NSNumber?' to expected argument type 'AutoreleasingUnsafeMutablePointer<AnyObject?>' error

I have this script use to check whether the *downloaded file from iCloud is available or not. But unfortunately I encountered error Cannot convert value of type 'inout NSNumber?' to expected argument type 'AutoreleasingUnsafeMutablePointer<AnyObject?>' in some lines of code. Please help me to solve this issue because it is my first time to create a code to check whether the downloaded file is available in the icloud or not.
Please refer to the image below as sample of the error and also codes are available below for your reference. Hope you could help me. Thank you.
Sample screenshot of error
//-------------------------------------------------------------------
// ダウンロードできるか判定 Judgment or can be downloaded
//-------------------------------------------------------------------
func downloadFileIfNotAvailable(_ file: URL?) -> Bool {
var isIniCloud: NSNumber? = nil
do {
try (file as NSURL?)?.getResourceValue(&isIniCloud, forKey: .isUbiquitousItemKey)
if try (file as NSURL?)?.getResourceValue(&isIniCloud, forKey: .isUbiquitousItemKey) != nil {
if isIniCloud?.boolValue ?? false {
var isDownloaded: NSNumber? = nil
if try (file as NSURL?)?.getResourceValue(&isDownloaded, forKey: .ubiquitousItemIsDownloadedKey) != nil {
if isDownloaded?.boolValue ?? false {
return true
}
performSelector(inBackground: #selector(startDownLoad(_:)), with: file)
return false
}
}
}
} catch {
}
return true
}
It looks like you copied and pasted some really old code. Besides, this is Swift, not Objective-C. Do not use NSURL or getResourceValue. Your code should look more like this:
if let rv = try file?.resourceValues(forKeys: [.isUbiquitousItemKey]) {
if let isInCloud = rv.isUbiquitousItem {
// and so on
}
}
And so on; the same pattern applied to other keys. Note that there is no .ubiquitousItemIsDownloadKey either. You can condense things like this:
if let rv = try file?.resourceValues(
forKeys: [.isUbiquitousItemKey, .ubiquitousItemDownloadingStatusKey]) {
if let isInCloud = rv.isUbiquitousItem {
if let status = rv.ubiquitousItemDownloadingStatus {
if status == .downloaded {
}
}
}
}

generic tap function for XCUIApplication

We are trying to migrate from UIAutomation to XCUITests.
For the UIAutomation we came up with a handy 'tapOnName' function which just crawled thru a whole sub element tree and tapped on the element with the first match.
function log(msg) {
UIALogger.logDebug(msg);
}
//recursive function crawling thru an elements hierarchy
//and tapping on the first match of accessibilityIdentifier
//or button text
function tapOnNameWithRoot(name,el) {
if (el.name()==name && el.isVisible()) {
log("tap on itt!!!")
el.tap();
return true;
}
if (el.toString()=="[object UIAButton]" && el.label()==name) {
log("tap on Button!!!")
el.tap();
return true;
}
var elements=el.elements();
if (elements===null || elements===undefined) {
log("elements null or undefined for:"+el.toString());
return false;
}
for(var i=0,len=elements.length ;i<len;i++) {
if (tapOnNameWithRoot(name,elements[i])) {
return true;
}
}
return false;
}
var win = UIATarget.localTarget().frontMostApp().mainWindow();
//for ex taps on a button with the text "pushme" in the
//main UIWindow
tapOnNameWithRoot("pushme",win);
No the question : is it possible to implement the same function using XCUIApplication ?
There is shorthand support for this function in XCTest.
For tapping the first match out of any element, you can get all elements and tap the first one:
let app = XCUIApplication()
let element = app.descendentsMatchingType(.Any)["someIdentifier"]
element.tap()
If you know what type of element it is going to be, it's better to filter by that type first:
let app = XCUIApplication()
let element = app.buttons["someIdentifier"]
element.tap()
Are you looking for something like this:
func tapBasedOnAccessibilityIdentifier(elementType elementType: XCUIElementQuery, accessibilityIdentifier: String) {
var isElementExist = false
for element in elementType.allElementsBoundByIndex {
if element.label == accessibilityIdentifier {
element.tap()
isElementExist = true
break
}
}
if !isElementExist {
XCTFail("Failed to find element")
}
}
where you call the method in the test like:
tapBasedOnAccessibilityIdentifier(elementType: app.staticTexts, accessibilityIdentifier: "Accessibility Identifier")
You can tweak it a little so that it cover all the requirements.

SocketScan Getting the Battery Level in Swift

Whatever I seem to try I cannot currently get back the Battery level from the iOS/SocketScan API. I am using version 10.3.36, here is my code so far:
func onDeviceArrival(result: SKTRESULT, device deviceInfo: DeviceInfo!) {
print("onDeviceArrival:\(deviceInfo.getName())")
scanApiHelper.postGetBattery(deviceInfo, target: self, response: #selector(onGetBatteryInfo))
}
func onGetBatteryInfo(scanObj: ISktScanObject) {
let result:SKTRESULT = scanObj.Msg().Result()
print("GetBatteryInfo status:\(result)")
if (result == ESKT_NOERROR) {
let batterylevel = scanObj.Property().getUlong()
print("Battery is:\(batterylevel)")
} else {
print("Error GetBatteryInfo status:\(result)")
}
However, the values I get back are:
GetBatteryInfo status:0
Battery is:1677741312
If my code is correct then how do I make the Battery result I get back a meaningful result, like a percentage? If I'm way off then how do I get back info like the battery level, firmware version etc?
Thanks
David
EDIT: SKTBATTERY_GETCURLEVEL isn't supported in Swift. However, the docs explain that the battery level response includes the min, current and max levels encoded in the first, second and third bytes, respectively.
The following is equivalent to using SKTBATTERY_GETCURLEVEL
Swift
func onGetBatteryInfo(scanObj: ISktScanObject) {
let result:SKTRESULT = scanObj.Msg().Result()
if(SKTSUCCESS(result)){
let batteryInfo = scanObj.Property().getUlong();
let batteryMin = ((batteryInfo >> 4) & 0xff);
let batteryCurrent = ((batteryInfo >> 8) & 0xff);
let batteryMax = ((batteryInfo >> 12) & 0xff);
let batteryPercentage = batteryCurrent / (batteryMax - batteryMin);
print("Battery is:\(batteryPercentage)")
self.setBatteryLevel = batteryPercentage
self.tableView.reloadData
} else {
print("Error GetBatteryInfo status:\(result)")
}
}
Objective-C
-(void) onGetBatteryInfo:(ISktScanObject*)scanObj {
SKTRESULT result=[[scanObj Msg]Result];
if(SKTSUCCESS(result)){
long batteryLevel = SKTBATTERY_GETCURLEVEL([[scanObj Property] getUlong]);
NSLog(#"BatteryInfo %ld", batteryLevel);
[self setBatteryLevel:batteryLevel];
[self.tableView reloadData];
} else {
NSLog(#"Error GetBatteryInfo status: %ld",result);
}
}
Here's code I use. Theres a variable defined in appDelegate for the batteryPercentage, and that is read when the v value is needed. The value is updated each 120 seconds by a timer, this way actions can occur as the level drops etc.
func onBatteryLevel (scanObj: ISktScanObject) {
let result: SKTRESULT = scanObj.Msg().Result()
if (SKTRESULT(result) > -1) {
let property: ISktScanProperty = scanObj.Property()
var batteryLevel = property.getUlong()
#if arch(x86_64) || arch(arm64)
batteryLevel = (batteryLevel<<(48))>>(56)
#else
batteryLevel = (batteryLevel<<(48-32))>>(56-32)
#endif
batteryPercentage = Int(batteryLevel)
} else {
debug ("data error \(result)")
}
}
For Swift 4 I just came across this problem and came up with the following solution.
var lastDeviceConnected : CaptureHelperDevice? {
didSet {
guard let lastDevice = self.lastDeviceConnected else { return }
lastDevice.getBatteryLevelWithCompletionHandler { result, batteryLevel in
guard result == SKTResult.E_NOERROR, let batteryLevel = batteryLevel else { return }
let minimum = SKTHelper.getMinimumLevel(fromBatteryLevel: Int(batteryLevel))
let maximum = SKTHelper.getMaximumLevel(fromBatteryLevel: Int(batteryLevel))
let current = SKTHelper.getCurrentLevel(fromBatteryLevel: Int(batteryLevel))
print("minimum: \(minimum)")
print("maximum: \(maximum)")
print("current: \(current)")
// current is out battery level in %
// minimum and maximum could for example be used for
// for a slider or something that visually presents
// the battery status
}
}
}
In my example I'm not handling the case that there could be no device or that the battery status might not have been retrieved as expected. I simply guard / return. In your example you might want to handle the issue.

Read a text file line by line in Swift?

I just started learning Swift. I have got my code to read from the text file, and the App displays the content of the entire text file. How can I display line by line and call upon that line multiple times?
TextFile.txt contains the following:
1. Banana
2. Apple
3. pear
4. strawberry
5. blueberry
6. blackcurrant
The following is what currently have..
if let path = NSBundle.mainBundle().pathForResource("TextFile", ofType: "txt"){
var data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: nil)
if let content = (data){
TextView.text = content
}
If there is another way of doing this please let me know. It would be much appreciated.
Swift 3.0
if let path = Bundle.main.path(forResource: "TextFile", ofType: "txt") {
do {
let data = try String(contentsOfFile: path, encoding: .utf8)
let myStrings = data.components(separatedBy: .newlines)
TextView.text = myStrings.joined(separator: ", ")
} catch {
print(error)
}
}
The variable myStrings should be each line of the data.
The code used is from:
Reading file line by line in iOS SDK written in Obj-C and using NSString
Check edit history for previous versions of Swift.
Swift 5.5
The solution below shows how to read one line at a time. This is quite different from reading the entire contents into memory. Reading line-by-line scales well if you have a large file to read. Putting an entire file into memory does not scale well for large files.
The example below uses a while loop that quits when there are no more lines, but you can choose a different number of lines to read if you wish.
The code works as follows:
create a URL that tells where the file is located
make sure the file exists
open the file for reading
set up some initial variables for reading
read each line using getLine()
close the file and free the buffer when done
You could make the code less verbose if you wish; I have included comments to explain what the variables' purposes are.
Swift 5.5
import Cocoa
// get URL to the the documents directory in the sandbox
let home = FileManager.default.homeDirectoryForCurrentUser
// add a filename
let fileUrl = home
.appendingPathComponent("Documents")
.appendingPathComponent("my_file")
.appendingPathExtension("txt")
// make sure the file exists
guard FileManager.default.fileExists(atPath: fileUrl.path) else {
preconditionFailure("file expected at \(fileUrl.absoluteString) is missing")
}
// open the file for reading
// note: user should be prompted the first time to allow reading from this location
guard let filePointer:UnsafeMutablePointer<FILE> = fopen(fileUrl.path,"r") else {
preconditionFailure("Could not open file at \(fileUrl.absoluteString)")
}
// a pointer to a null-terminated, UTF-8 encoded sequence of bytes
var lineByteArrayPointer: UnsafeMutablePointer<CChar>? = nil
// see the official Swift documentation for more information on the `defer` statement
// https://docs.swift.org/swift-book/ReferenceManual/Statements.html#grammar_defer-statement
defer {
// remember to close the file when done
fclose(filePointer)
// The buffer should be freed by even if getline() failed.
lineByteArrayPointer?.deallocate()
}
// the smallest multiple of 16 that will fit the byte array for this line
var lineCap: Int = 0
// initial iteration
var bytesRead = getline(&lineByteArrayPointer, &lineCap, filePointer)
while (bytesRead > 0) {
// note: this translates the sequence of bytes to a string using UTF-8 interpretation
let lineAsString = String.init(cString:lineByteArrayPointer!)
// do whatever you need to do with this single line of text
// for debugging, can print it
print(lineAsString)
// updates number of bytes read, for the next iteration
bytesRead = getline(&lineByteArrayPointer, &lineCap, filePointer)
}
If you have a huge file and don't want to load all data to memory with String, Data etc. you can use function readLine() which reads content from standard input line by line until EOF is reached.
let path = "path/file.txt"
guard let file = freopen(path, "r", stdin) else {
return
}
defer {
fclose(file)
}
while let line = readLine() {
print(line)
}
This is not pretty, but I believe it works (on Swift 5). This uses the underlying POSIX getline command for iteration and file reading.
typealias LineState = (
// pointer to a C string representing a line
linePtr:UnsafeMutablePointer<CChar>?,
linecap:Int,
filePtr:UnsafeMutablePointer<FILE>?
)
/// Returns a sequence which iterates through all lines of the the file at the URL.
///
/// - Parameter url: file URL of a file to read
/// - Returns: a Sequence which lazily iterates through lines of the file
///
/// - warning: the caller of this function **must** iterate through all lines of the file, since aborting iteration midway will leak memory and a file pointer
/// - precondition: the file must be UTF8-encoded (which includes, ASCII-encoded)
func lines(ofFile url:URL) -> UnfoldSequence<String,LineState>
{
let initialState:LineState = (linePtr:nil, linecap:0, filePtr:fopen(fileURL.path,"r"))
return sequence(state: initialState, next: { (state) -> String? in
if getline(&state.linePtr, &state.linecap, state.filePtr) > 0,
let theLine = state.linePtr {
return String.init(cString:theLine)
}
else {
if let actualLine = state.linePtr { free(actualLine) }
fclose(state.filePtr)
return nil
}
})
}
Here is how you might use it:
for line in lines(ofFile:myFileURL) {
print(line)
}
Probably the simplest, and easiest way to do this in Swift 5.0, would be the following:
import Foundation
// Determine the file name
let filename = "main.swift"
// Read the contents of the specified file
let contents = try! String(contentsOfFile: filename)
// Split the file into separate lines
let lines = contents.split(separator:"\n")
// Iterate over each line and print the line
for line in lines {
print("\(line)")
}
Note: This reads the entire file into memory, and then just iterates over the file in memory to produce lines....
Credit goes to: https://wiki.codermerlin.com/mediawiki/index.php/Code_Snippet:_Print_a_File_Line-by-Line
Update for Swift 2.0 / Xcode 7.2
do {
if let path = NSBundle.mainBundle().pathForResource("TextFile", ofType: "txt"){
let data = try String(contentsOfFile:path, encoding: NSUTF8StringEncoding)
let myStrings = data.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
print(myStrings)
}
} catch let err as NSError {
//do sth with Error
print(err)
}
Also worth to mention is that this code reads a file which is in the project folder (since pathForResource is used), and not in e.g. the documents folder of the device
You probably do want to read the entire file in at once. I bet it's very small.
But then you want to split the resulting string into an array, and then distribute the array's contents among various UI elements, such as table cells.
A simple example:
var x: String = "abc\ndef"
var y = x.componentsSeparatedByString("\n")
// y is now a [String]: ["abc", "def"]
One more getline solution:
Easy to use. Just copy past.
Tested on real project.
extension URL
{
func foreachRow(_ mode:String, _ rowParcer:((String, Int)->Bool) )
{
//Here we should use path not the absoluteString (wich contains file://)
let path = self.path
guard let cfilePath = (path as NSString).utf8String,
let m = (mode as NSString).utf8String
else {return}
//Open file with specific mode (just use "r")
guard let file = fopen(cfilePath, m)
else {
print("fopen can't open file: \"\(path)\", mode: \"\(mode)\"")
return
}
//Row capacity for getline()
var cap = 0
var row_index = 0
//Row container for getline()
var cline:UnsafeMutablePointer<CChar>? = nil
//Free memory and close file at the end
defer{free(cline); fclose(file)}
while getline(&cline, &cap, file) > 0
{
if let crow = cline,
// the output line may contain '\n' that's why we filtered it
let s = String(utf8String: crow)?.filter({($0.asciiValue ?? 0) >= 32})
{
if rowParcer(s, row_index)
{
break
}
}
row_index += 1
}
}
}
Usage:
let token = "mtllib "
var mtlRow = ""
largeObjFileURL.foreachRow("r"){ (row, i) -> Bool in
if row.hasPrefix(token)
{
mtlRow = row
return true // end of file reading
}
return false // continue file reading
}
Here is an example of writeing and reading a text file one line at a time
in Swift version 5. Reads one line in at a time and includes EOF detection
//
// main.swift
// IO
//
// Created by Michael LeVine on 8/30/22.
//
import Foundation
let file = "file.txt" //this is the file. we will write to and read from it
let text = "some text\n" //just a text
// test file will be placed on deasktop
let dir = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first
let fileURL = dir!.appendingPathComponent(file).path
let fileURL2 = dir!.appendingPathComponent(file)
let fileManager = FileManager.default
// the following variable used by eof detection which also use var fileManager internally
var eofOffset: UInt64 = 0
if fileManager.fileExists(atPath: fileURL) {
do { try fileManager.removeItem(atPath: fileURL)}
catch {
print("Error removeing old \(fileURL)")
exit(1)
}
}
// create the new file
fileManager.createFile(atPath: fileURL, contents:Data(" ".utf8), attributes: nil)
var fileHandle = FileHandle(forWritingAtPath: fileURL)
//writing
for _ in 1...10 {
fileHandle!.write(text.data(using: .utf8)!)
}
do {
try fileHandle!.close()
}
catch { print("write close error \(error)")
exit(1)
}
// now to read text file by 2 methods
// first use String to read whole file in one gulp
let contents = try! String(contentsOfFile: fileURL)
let lines = contents.split(separator: "\n")
var i: Int = 0
// print out one way
for line in lines {
print("\(i) \(line)")
i=i+1
}
// printout another way
for j in 0...9 {
print("\(i) \(j) \(lines[j])")
i = i + 1
}
//Open up to see about reading line at a time
fileHandle = FileHandle(forReadingAtPath: fileURL)
eofInit() // must be called immediately after fileHandle init
var outputLine: String = ""
i = 0
// read a line and print it out as recieved
while true {
outputLine = getLine()
if eofTest(){
if outputLine.count > 0 {
print("\(i) \(outputLine)")
}
exit(1)
}
print("\(i) \(outputLine)")
i = i + 1
}
// function reads one character at each call and returns it as a 1 character string
// is called only by "getLine"
func getChar() -> String {
var ch: Data
if eofTest() {
return ""
}
do {
try ch = fileHandle!.read(upToCount: 1)! // read 1 character from text file
} catch { print("read 1 char \(error)")
exit(1)
}
let ch2: UnicodeScalar = UnicodeScalar(ch[0]) // convert to unicode scaler as intermediate value
let ch3: String = String(ch2) // Now create string containing that one returned character
return ch3 // and pass to calling function
}
// read in whole line one character at a time -- assumes line terminated by linefeed
func getLine() -> String {
var outputLine : String = ""
var char : String = ""
// keep fetching characters till line feed/eof found
lineLoop:
while true { // its an infinite loop
if eofTest() {
break lineLoop
}
char = getChar() // get next character
if char == "\n" { // test for linefeed
break lineLoop // if found exit loop
}
outputLine.append(char) // lf not found -- append char to output line
}
return outputLine // got line -- return it to calling routine
}
//eof handleing
//init routine must be called immediately after fileHandle inited to get current position
// at start of file
func eofInit()
{ var beginningOffset: UInt64 = 0
do {
try beginningOffset = fileHandle!.offset()
try eofOffset = fileHandle!.seekToEnd()
try fileHandle!.seek(toOffset: beginningOffset)
} catch {
print("Init eof detection error \(error)")
}
}
func eofTest() -> Bool{
var current: UInt64 = 0
do {
current = try fileHandle!.offset()
} catch {
print("eof test get current \(error)")
exit(1)
}
if current < eofOffset {
return false
} else {
return true
}
}
Based on Jason Cross answer simplified version line by line reader(gist).
import Darwin
class FileLineReader {
init?(path: String, removeNewLineOnEnd: Bool = true) {
file = fopen(path, "r")
self.removeNewLineOnEnd = removeNewLineOnEnd
if file == nil {
return nil
}
}
deinit {
fclose(file)
}
var iterator: AnyIterator<String> {
return AnyIterator(self.getNextLine)
}
func getNextLine() -> String? {
var line: UnsafeMutablePointer<CChar>!
var linecap: Int = 0
defer { free(line) }
if getline(&line, &linecap, file) > 0 {
if removeNewLineOnEnd {
var i = 0
while line[i] != 0 { i += 1 }
if i > 0 && line[i-1] == 10 { // new line symbol
line[i-1] = 0
}
}
return String(cString: line)
} else {
return nil
}
}
private let file: UnsafeMutablePointer<FILE>!
private let removeNewLineOnEnd: Bool
}
iUrii approach may not work if you need to open several files.

How to do a "not in" query in Parse

I'm building a sort of hot or not style app in Swift where the user can vote: HOT, NOT and MAYBE on an image, respectively.
For every time the user gets to a image, they vote by tapping the IBAction, which triggers a query that shows the result of the total votes and total hots from Parse as shown in my code below.
I plan to have 1,000 images.
Can I preload some of the objectIDs that correspond to each respective image, and then when the user votes on the image, the data is already preloaded/queried from parse? How would I go about that? Someone recommended in my previous question to use a NOT IN query in Parse. How do I do a NOT IN query in Parse and how would I go about doing that?
For now, I'm writing a query for each ObjectID which would take 1000 queries from 1000 different images... Obviously unscalable.
Further code explanations:
The swipePosition variable is just a counter that counts which image the user is on. The images being stored are in an Array for now stored on Xcode. Maybe they can be preloaded as well if they are stored on Parse?
(I am only showing the "hotButtonQuery" function, but there is also a Not and Maybe buttonQuery function.)
Is there a way to simply this code so that it's scalable? Because, as of now, there's no way I can scale past 25 images.
func hotButtonQuery() {
if swipePosition == 0 {
var query = PFQuery(className:"UserData")
query.getObjectInBackgroundWithId("RlvK3GhfqE") {
(userData: PFObject!, error: NSError!) -> Void in
if error != nil {
println(error)
}
else {
userData.incrementKey("totalVotes", byAmount: 1)
userData.incrementKey("hot", byAmount: 1)
var updateTotalVotesUILabel = userData.objectForKey("totalVotes") as NSInteger
var updateHotsUILabel = userData.objectForKey("hot") as NSInteger
userData.saveInBackground()
println("parse was updated!")
self.totalVotesLabel.text = String(updateTotalVotesUILabel)
self.totalHotsLabel.text = String(updateHotsUILabel)
}
}
} else if swipePosition == 1 {
var query = PFQuery(className:"UserData")
query.getObjectInBackgroundWithId("30WlVtgurP") {
(userData: PFObject!, error: NSError!) -> Void in
if error != nil {
println(error)
}
else {
userData.incrementKey("totalVotes", byAmount: 1)
userData.incrementKey("hot", byAmount: 1)
var updateTotalVotesUILabel = userData.objectForKey("totalVotes") as NSInteger
var updateHotsUILabel = userData.objectForKey("hot") as NSInteger
//println(userData.objectForKey("totalVotes"))
//println("total HOTs:")
//println(userData.objectForKey("hot"))
userData.saveInBackground()
println("parse was updated!")
self.totalVotesLabel.text = String(updateTotalVotesUILabel)
self.totalHotsLabel.text = String(updateHotsUILabel)
}
}
} else if swipePosition == 3 {
var query = PFQuery(className:"UserData")
query.getObjectInBackgroundWithId("5D6ARjk3xS") {
(userData: PFObject!, error: NSError!) -> Void in
if error != nil {
println(error)
}
else {
userData.incrementKey("totalVotes", byAmount: 1)
userData.incrementKey("hot", byAmount: 1)
var updateTotalVotesUILabel = userData.objectForKey("totalVotes") as NSInteger
var updateHotsUILabel = userData.objectForKey("hot") as NSInteger
//println(userData.objectForKey("totalVotes"))
//println("total HOTs:")
//println(userData.objectForKey("hot"))
userData.saveInBackground()
println("parse was updated!")
self.totalVotesLabel.text = String(updateTotalVotesUILabel)
self.totalHotsLabel.text = String(updateHotsUILabel)
}
}
}
just use
query.whereKey("key", doesNotMatchKey: "matchcheck", inQuery: innerQuery)
An example of Not In:
var query = PFUser.query()
if (friendsFilter){
var friendsRelation:PFRelation = PFUser.currentUser().relationForKey("friendsRelation")
query = friendsRelation.query()
}
else{
var friendsRelation:PFRelation = PFUser.currentUser().relationForKey("friendsRelation")
var innerQuery = friendsRelation.query()
query = PFUser.query()
query.whereKey("username", doesNotMatchKey: "username", inQuery: innerQuery)

Resources