PFUser返回NIl?

时间:2015-11-24 17:46:17

标签: ios swift parse-platform swift2

我试图通过部分遵循Makestagram教程来解析中设置一个类似的系统。

我花了好几个小时试图调试这个并没有运气..

DetailViewController: 

@IBAction func likeButtonTapped(sender: AnyObject) {
    merchant!.toggleLikePost(PFUser.currentUser()!)
}

此声明正在返回:

unexpectedly found nil while unwrapping an Optional value
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
The process has been returned to the state before expression evaluation.

其余代码如下:

DetailViewController:

var likeBond: Observable<[PFUser]?>! = Observable(nil)
var parseHelper = ParseHelper()

var likeDisposable: DisposableType?

var merchant: Merchant? {
    didSet {

        likeDisposable!.dispose()


        if let merchant = merchant {
            likeDisposable = merchant.likes.observe { (value: [PFUser]?) -> () in
                if let value = value {
                    self.likesButton.selected = value.contains(PFUser.currentUser()!)
                    self.likesImageView.hidden = (value.count == 0)
                } else {
                    self.likesLabel.text = ""
                    self.likesButton.selected = false
                    self.likesImageView.hidden = true
                }

            }
        }
    }
}

商人类:

func toggleLikePost(user: PFUser) {
    if (doesUserLikeMerchant(user)) {
        // if image is liked, unlike it now
        // 1
        likes.value = likes.value?.filter { $0 != user }
        ParseHelper.unlikePost(user, merchant: self)
    } else {
        // if this image is not liked yet, like it now
        // 2
        likes.value?.append(user)
        ParseHelper.likePost(user, merchant: self)
    }
}

func doesUserLikeMerchant(user: PFUser) -> Bool {
    if let likes = likes.value {
        return likes.contains(user)
    } else {
        return false
    }
}

ParseHelper类:

static func likePost(user: PFUser, merchant: Merchant) {
    let likedObject = PFObject(className: ParseLikeClass)
    likedObject.setObject(user, forKey: parseLikeFromUser)
    likedObject.setObject(merchant, forKey: ParseLikeToPost)

    likedObject.saveInBackgroundWithBlock(ErrorHandling.errorHandlingCallback)
}

 static func unlikePost(user: PFUser, merchant: Merchant) {
    let query = PFQuery(className: ParseLikeClass)
    query.whereKey(parseLikeFromUser, equalTo: user)
    query.whereKey(ParseLikeToPost, equalTo: merchant)

    query.findObjectsInBackgroundWithBlock {
        (results: [PFObject]?, error: NSError?) -> Void in
        if let error = error {
            ErrorHandling.defaultErrorHandler(error)
        }

        if let results = results {
            for likes in results {
                likes.deleteInBackgroundWithBlock(ErrorHandling.errorHandlingCallback)
            }
        }
    }
}

感谢任何帮助..如果需要,我会添加git repo。

1 个答案:

答案 0 :(得分:0)

您需要先在代理中调用PFUser.enableAutomaticUser()。 调用此方法后,currentUser将始终具有值。