斯威夫特 - 的Json - API经理 [英] Swift - Json - Api Manager

查看:162
本文介绍了斯威夫特 - 的Json - API经理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我目前的工作在一个斯威夫特阿比经理,我得到了什么至今:

Hi there i am currently working on a Api Manager in Swift, what i got so far:

import Foundation
import CoreData
import Alamofire
import SwiftyJSON

class ApiManager {

    var data: NSArray = []

    func getApi() -> NSArray {

        let user:String = "user"
        let password:String = "password"

        Alamofire.request(.GET, "http://localhost/api/")
            .authenticate(user: user, password: password)
            .responseJSON{ (request, response, jsonData, error) in

                if let jsonData1 = jsonData {

                    if let jsonData2 = JSON(jsonData1).dictionaryObject {

                        self.data = jsonData2["data"] as! NSArray

                    }

                }

        }

        return data

    }

}

JSON API使用是正确的,但有某事不对我的SWIFT code,但我不知道它是什么,

The JSON Api is correct, but there is sth wrong with my swift code, but i am not sure what it is,

当我把这个经理:

let response = ApiManager().getApi()
println(response)

我只是得到空方括号:

i just get empty brackets:

(
)

任何人都可以帮助我?

Anybody could help me with this?

问候和感谢!

推荐答案

这是一个设计缺陷。你不应该做这种方式。你的 getApi()方法应该如果响应成功,这将是执行的成功块。这里是一个可能的解决方案:

This is a faulty design. You should NOT do it this way. Your getApi() method should have a success block which would be executed if the response was successful. Here is one possible solution:

static func getApi(success:( (data:NSArray) -> () )) {

    let user:String = "user"
    let password:String = "password"

    Alamofire.request(.GET, "http://localhost/api/")
        .authenticate(user: user, password: password)
        .responseJSON{ (request, response, jsonData, error) in

            if let jsonData1 = jsonData {

                if let jsonData2 = JSON(jsonData1).dictionaryObject {

                    success(jsonData2 as! NSArray)

                }

            }

    }

    return data

}

所以,如果你要打印的反应,你会做这样的事情:

So, if you want to print the response, you'll do something like:

APIManager.getApi {
 println($0)
}

这篇关于斯威夫特 - 的Json - API经理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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