从功能的迅速恢复阵列 [英] Return Array from Function in Swift

查看:126
本文介绍了从功能的迅速恢复阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我是一个有点新的迅速和对象的C以及和想知道如果有人可以帮助我一下。

So im a bit new to swift and object-c as well and was wondering if someone could help me out a bit.

我已经习惯了创建通常是一个utils的文件,在那里我有我的编程经常使用的功能。

I'm used to creating usually a utils file where I have functions I use often in programming.

在这种情况下,即时试图从另一个调用迅速文件中的函数和返回数据的数组。

In this case im trying to call a function from another swift file and return an array of data.

例如在我的mainViewController.swift IM调用该函数:

For example in my mainViewController.swift im calling the function:

var Data = fbGraphCall()

在Utils.swift文件我有我试着去得到它返回收集的数据阵列的功能。

In the Utils.swift file I have a function that Im trying to get it to return an array of data collected.

func fbGraphCall() -> Array<String>{

var fbData: [String] = [""]

if (FBSDKAccessToken.currentAccessToken() != nil){

    // get fb info
    var userProfileRequestParams = [ "fields" : "id, name, email, about, age_range, address, gender, timezone"]

    let userProfileRequest = FBSDKGraphRequest(graphPath: "me", parameters: userProfileRequestParams)

    let graphConnection = FBSDKGraphRequestConnection()

    graphConnection.addRequest(userProfileRequest, completionHandler: { (connection: FBSDKGraphRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
        if(error != nil) {

            println(error)

        } else {

            // DEBUG
            println(result)


            let fbEmail = result.objectForKey("email") as! String

            // DEBUG
            println(fbEmail)

            fbData.append("\(fbEmail)")

            let fbID = result.objectForKey("id") as! String


            if(fbEmail != "") {
                PFUser.currentUser()?.username = fbEmail
                PFUser.currentUser()?.saveEventually(nil)
            }

            println("Email: \(fbEmail)")

            println("FBUserId: \(fbID)")


        }


    })

    graphConnection.start()
}

println(fbData)
return fbData
}

我可以证实,即时通讯从Facebook获取fbEmail和fbID回到我的调试语句,但正如我说我还在如何将数据返回新的。

I can confirm that im getting the fbEmail and fbID back from facebook with my debug statements but as I said im still new on how to return data back.

理想我平时想一个数组回来,如果它的多个值,或者得到类似 Data.fbEmail,Data.fbID 数据或数组也许像<能力code> [电子邮件:email@gmail.com,ID:1324134124zadfa]

Ideally I usually want an array back if its more than one value or the ability to get back data like Data.fbEmail, Data.fbID or an array maybe like ["email" : "email@gmail.com", "id" : "1324134124zadfa"]

当我打的返回语句的空白..所以不知道为什么常量不守值,或将值传递到我的fbData阵..我想fbData.append(fbEmail)为例。

When I hit the return statement its blank.. so not sure why the constants are not keeping values or passing values into my fbData array.. I'm trying fbData.append(fbEmail) for example ..

这是什么可能是错误什么想法?

any thoughts on what might be wrong?

推荐答案

graphConnection.addRequest 是一个异步功能,您正试图同步返回一个字符串数组回来。因为 graphConnection.addRequest 在后台进行,以避免阻塞主线程这是行不通的。所以,而不是返回的数据直接进行完成处理程序。那么你的函数会成为这样的:

The graphConnection.addRequest is an asynchronous function and you are trying to synchronously return the array of strings back. This won't work because the graphConnection.addRequest is done in the background to avoid blocking the main thread. So instead of returning the data directly make a completion handler. Your function would then become this:

func fbGraphCall(completion: ([String]) -> Void, errorHandler errorHandler: ((NSError) -> Void)?) {
    if (FBSDKAccessToken.currentAccessToken() != nil) {
        // get fb info
        var userProfileRequestParams = [ "fields" : "id, name, email, about, age_range, address, gender, timezone"]

        let userProfileRequest = FBSDKGraphRequest(graphPath: "me", parameters: userProfileRequestParams)

        let graphConnection = FBSDKGraphRequestConnection()

        graphConnection.addRequest(userProfileRequest, completionHandler: { (connection: FBSDKGraphRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
            if(error != nil) {
                println(error)
                errorHandler?(error!)
            } else {
                var fbData = [String]() // Notice how I removed the empty string you were putting in here.
                // DEBUG
                println(result)


                let fbEmail = result.objectForKey("email") as! String

                // DEBUG
                println(fbEmail)

                fbData.append("\(fbEmail)")

                let fbID = result.objectForKey("id") as! String


                if(fbEmail != "") {
                    PFUser.currentUser()?.username = fbEmail
                    PFUser.currentUser()?.saveEventually(nil)
                }

                println("Email: \(fbEmail)")

                println("FBUserId: \(fbID)")

                completion(fbData)
            }


        })

        graphConnection.start()
    }
}

我增加了完成处理并得到按什么需要执行的错误处理程序块。

I added the completion handler and the error handler blocks that get executed according to what's needed.

现在在调用网站,你可以做这样的事情:

Now at the call site you can do something like this:

fbGraphCall( { println($0) // $0 refers to the array of Strings retrieved }, errorHandler:  { println($0) // TODO: Error handling  }) // Optionally you can pass `nil` for the error block too incase you don't want to do any error handling but this is not recommended.

修改

为了使用,你会做这样的事情的变量在调用点

In order to use the variables you would do something like this at the call site

 fbGraphCall( { array in
      dispatch_async(dispatch_get_main_queue(), {  // Get the main queue because UI updates must always happen on the main queue.
             self.fbIDLabel.text = array.first // array is the array we received from the function so make sure you check the bounds and use the right index to get the right values.
             self.fbEmailLabel.text = array.last 
      })
 }, errorHandler:  { 
        println($0) 
        // TODO: Error handling  
  })

这篇关于从功能的迅速恢复阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆