Swift控制流程:

时间:2015-03-06 00:54:09

标签: facebook swift control-flow

下面在我的代码中,我试图使用Facebook SDK获取我的朋友列表并在另一个视图控制器上显示它们。我在函数createFriendsInfo(data : NSArray)中调用函数loginViewShowingLoggedInUser。正在调用该函数,数据正在数组中填充。

问题是在createFriendsInfo中的循环完成填充数组中的数据后,控件直接进入视图控制器。相反,它应该首先在函数循环之后完成执行语句,然后控件应该返回loginViewShowingLoggedInUserperformSegueWithIdentifier:应该执行。

我是Swift的新手,我需要一些帮助来理解代码中的控制流程。

import Foundation
import UIKit

class FBViewController : UIViewController, FBLoginViewDelegate {


    @IBOutlet var fbLogin: FBLoginView!
    var friendNames : [String] = []
    var friendPics : [UIImage] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        //var fbl: FBLoginView = FBLoginView() //create login button on UIController
        //self.view.addSubview(fbl)
        // Do any additional setup after loading the view, typically from a nib.
        self.fbLogin.delegate = self
        self.fbLogin.readPermissions = ["public_profile", "email", "user_friends"]


    }

    func createFriendsInfo(data : NSArray)
    {
        println("Start Create")
        for i in 0...data.count {
            let valueDict : NSDictionary = data[i] as NSDictionary
            let userID = valueDict.objectForKey("id") as String
            self.friendNames.append(valueDict.objectForKey("name") as String)
            let id = valueDict.objectForKey("name") as String
            var url = NSURL (string : "http://graph.facebook.com/\(userID)/picture?type=large")
            let urlRequest = NSURLRequest(URL: url!)
            let session = NSURLSession.sharedSession()

            var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
            var error: NSErrorPointer = nil
            if let ImageData : NSData = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: response, error:nil)?
            {
                var image = UIImage( data : ImageData)
                self.friendPics.append(image!)
                println("Image Appended")
            }
        }

        println("Create Friends Info \(self.friendNames.count) \(self.friendPics.count) ")
    }


    // Facebook Delegate Methods

    func loginViewShowingLoggedInUser(loginView : FBLoginView!) {

                println("Start Fetched")
                var friendsRequest : FBRequest = FBRequest.requestForMyFriends()
                friendsRequest.startWithCompletionHandler{(connection:FBRequestConnection!, result:AnyObject!, error:NSError!) -> Void in
                    var resultdict = result as NSDictionary
                    println("Result Dict: \(resultdict)")
                    var Data : NSArray = resultdict.objectForKey("data") as NSArray
                    self.createFriendsInfo(Data)
                    println("Perform \(self.friendNames.count) \(self.friendPics.count) ")
                    self.performSegueWithIdentifier("toFriendList", sender: self)
                    println("Perform \(self.friendNames.count) \(self.friendPics.count) ")
        //
                }

        //self.performSegueWithIdentifier("toFriendList", sender: self)

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func loginViewFetchedUserInfo(loginView : FBLoginView!, user: FBGraphUser) {
    }

    func loginViewShowingLoggedOutUser(loginView : FBLoginView!) {
        println("User Logged Out")
        self.friendNames = []
        self.friendPics = []
        println("Logout \(self.friendNames.count) \(self.friendPics.count) ")
    }

    func loginView(loginView : FBLoginView!, handleError:NSError) {
        println("Error: \(handleError.localizedDescription)")
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if((segue.identifier == "toFriendList" ) && (self.friendNames.count > 0))
        {
            var fl : friendList = segue.destinationViewController as friendList
            println("Prepare \(self.friendNames.count) \(self.friendPics.count) ")
            fl.name1 = self.friendNames
            fl.profilepics1 = self.friendPics
        }

    }






}

1 个答案:

答案 0 :(得分:1)

for中的createFriendsInfo循环上限错误;通常是0..<data.count。实际上,

for i in 0...data.count {
  let valueDict : NSDictionary = data[i] as NSDictionary
  // ...
<{1>}时

将“失败”。

但是,对于控制流,i == data.count完成处理程序最肯定不会在主队列上运行。这意味着friendsRequest将“迷失”。将您的代码更改为:

performSegueWithIdentifier

必须在主队列上执行所有UI操作。

请注意,您可能需要在func loginViewShowingLoggedInUser(loginView : FBLoginView!) { println("Start Fetched") var friendsRequest : FBRequest = FBRequest.requestForMyFriends() friendsRequest.startWithCompletionHandler{ (connection:FBRequestConnection!, result:AnyObject!, error:NSError!) -> Void in var resultdict = result as NSDictionary println("Result Dict: \(resultdict)") var Data : NSArray = resultdict.objectForKey("data") as NSArray self.createFriendsInfo(Data) println("Perform \(self.friendNames.count) \(self.friendPics.count) ") dispatch_async(dispatch_get_main_queue()) { self.performSegueWithIdentifier("toFriendList", sender: self) println("Perform \(self.friendNames.count) \(self.friendPics.count) ") // } } } 的闭包中将self声明为unowned(我忘记了当前的Swift状态)