使用会话

时间:2017-03-06 18:35:28

标签: ios objective-c swift

我尝试对后端服务器执行POST请求,并将其用于目标中的“ServiceUtils”类中的基本会话 - c

(AFHTTPSessionManager *)baseSessionManager {

        if (httpSessionManager) {
            return httpSessionManager;
        }

        httpSessionManager = [AFHTTPSessionManager manager];
        httpSessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
        [httpSessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [httpSessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

        // User agent for iOS app.
        NSString *userAgent = [NSString stringWithFormat:@"xxxxx Mobile iOS/%@ (%@ - %@ v%@)", [Utils appVersionWithBuild], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemName], [[UIDevice currentDevice] systemVersion]];

        [httpSessionManager.requestSerializer setValue:userAgent forHTTPHeaderField:@"User-Agent"];

        // Mobile auth 
        User *user = [User getUserWithContext:[NSManagedObjectContext MR_defaultContext]];
        NSString *mobileAuth = [[NSString stringWithFormat:@"%@--givemymoneybackdude", user.token] sha1];
        [httpSessionManager.requestSerializer setValue:mobileAuth forHTTPHeaderField:@"Mobile-Auth"];

        // Authorization
        NSString *authorization = [[NSString stringWithFormat:@"%@:X", user.token] stringBase64];
        [httpSessionManager.requestSerializer setValue:[NSString stringWithFormat:@"Basic %@", authorization] forHTTPHeaderField:@"Authorization"];

        // Locale
        if (user.locale) {
            [httpSessionManager.requestSerializer setValue:user.locale forHTTPHeaderField:@"Accept-Language"];
        }

        return httpSessionManager;
    }

以下是我在swift 2.3中尝试发出POST请求的代码

if let url = NSURL(string: "xxxxxxxx") {
            let session = ServicesUtils.baseSessionManager()
            let request = NSMutableURLRequest(URL: url)

            request.HTTPMethod = "POST"
            request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

            let jsonObject = ["token" : "Token String", "refresh_token" : "refresh_token String","expires_in" : "expires_in String", "user_id" : "uber_uuid", "token_type" : "Bearer"]


            request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(jsonObject, options: [])

            session.dataTaskWithRequest(request) { data, response, error in
                guard
                 error == nil &&
                        (response as? NSHTTPURLResponse)?.statusCode == 200
                    else {
                        print((response as? NSHTTPURLResponse)?.statusCode ?? "no status code")
                        print(error?.localizedDescription ?? "no error description")
                        return
                }
                }.resume()

尝试此操作后,我收到此错误:

  

请求失败:未授权(401)

我检查了标题,它没问题,但是这个问题正在发生。有人能告诉我为什么会这样吗?我怎么能在 jsonObject 里面传入一个包含其中值的“Integration”字典

1 个答案:

答案 0 :(得分:0)

本规范将帮助您...并使用Alomafire。

    Alamofire.request(requestUrl, method: .post, parameters: (parametersDictionary as NSDictionary) as? Parameters , encoding: JSONEncoding.default, headers: nil).responseJSON { response in


        if(response.result.error == nil){

            if((response.response?.statusCode)! < 500){

                if(response.response?.statusCode == 200){

                    if let JSON = response.result.value {


                        let dict = JSON as! NSDictionary
                        let status :Bool = dict["status"] as! Bool

                        if(status){
                            success(dict)
                        }else{
                            failure(dict["message"] as! String)
                        }
                    }
                }else{
                    failure("Something went wrong please try again")
                }
            }else{
                 failure("Something went wrong please try again")
            }
        }
    }
}

我希望以下链接可以为您提供帮助:https://github.com/Alamofire/Alamofire