首页 > 解决方案 > 无法通过 Swift 中的 V2 API 在 LinkedIn 上进行文本共享

问题描述

我可以通过 Linkedin V2 API 登录,并且可以获取个人资料图片、名字、姓氏和 UserId 以显示一些详细信息。

但是,我无法在 Linkedin V2 API 上进行文本分享。

这就是我使用之前获得的访问令牌获取个人数据的方式。

private func fetchPersonalData(_ tokenIn:String){
    
    MKProgress.show()
    
    //user details
    let requestUrl = "https://api.linkedin.com/v2/me?oauth2_access_token=\(tokenIn)"
   
    AF.request(requestUrl, method: .get ).responseData { (response) in
        
        switch response.result {
        case .failure(let error):
            print(error)
        
        case .success(let data):
            
            print("Success")
            
            do{
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                    print("JSON RESPONSE ====>>>> \(json) ")
                    
                    if let firstName = json["localizedFirstName"] as? String {
                        var preText = self._txtView.text ?? ""
                        preText = preText + "\n\nFirst Name :" + firstName
                        self._txtView.text = preText
                    }
                    
                    if let lastName = json["localizedLastName"] as? String {
                        var preText = self._txtView.text ?? ""
                        preText = preText + "\nLast Name :" + lastName
                        self._txtView.text = preText
                    }
                    
                    if let userId = json["id"] as? String {
                        self._currentUserId = userId
                        var preText = self._txtView.text ?? ""
                        preText = preText + "\nUserId        :" + userId
                        self._txtView.text = preText
                    }
                    
                    if let token = self.getAccessToken() {
                        self.fetchPersonalDisplayImage(token)
                    }
                    
                    
                }else{
                    print("failed to JSON serialize")
                }
                
            }catch let error as NSError {
                print("Failed to load: \(error.localizedDescription)")
            }
        }
        
        MKProgress.hide(true)
        
    }
}

当我尝试发短信分享时,它给了我错误

@IBAction func btnSharePressed(_ sender: UIButton) {
    
    guard let token = getAccessToken() else {
        print("Token not found")
        return
    }
    
    guard !_currentUserId.isEmpty else {
        print("User ID IS empty")
        return
    }
    
    //'Content-Type: application/json','X-Restli-Protocol-Version: 2.0.0','x-li-format: json','Authorization: Bearer '.$token
    let header1 :  HTTPHeaders = ["Content-Type": "application/json",
                                  "X-Restli-Protocol-Version":"2.0.0"]
    
    //oauth2_access_token=\(tokenIn)"
    let requestUrl = "https://api.linkedin.com/v2/ugcPosts?oauth2_access_token=\(token)"
    
    MKProgress.show(true)
    
    //JSON
    let shareCommentDic:NSDictionary = [
        "text": "Hello World! Share through LinkedIn SDK"
    ]
    
    let comDict:NSDictionary = [
        "shareCommentary" : shareCommentDic,
        "shareMediaCategory": "NONE"
    ]
    
    let specificDict:NSDictionary = [
        "com.linkedin.ugc.ShareContent" : comDict
    ]
    
    
    let visibilityDic:NSDictionary = [
        "com.linkedin.ugc.MemberNetworkVisibility":"PUBLIC",
    ]
    
    let mutDict:[String:Any] = ["author":"urn:li:person:\(_currentUserId)",
                                 "lifecycleState":"PUBLISHED",
                                 "specificContent":specificDict,
                                 "visibility":visibilityDic]
    
    //var input:String = ""
    
    var theJSONText = ""
    if let theJSONData = try? JSONSerialization.data(withJSONObject: mutDict, options: []) {
        theJSONText = String(data: theJSONData,encoding: .utf8) ?? "NA"
        print("JSON string = \(theJSONText)")
    }
    
    print("Parameters == \(mutDict)")
    
    AF.request(requestUrl, method: .post, parameters:mutDict , encoding:URLEncoding.default, headers: header1).responseData { (response) in
        
        switch response.result {
        case .failure(let error):
            print(error)
        //completion(nil)
        
        case .success(let data):
            
            
            print("Success")
            //completion(response.result)
            do{
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                    print("JSON RESPONSE ====>>>> \(json) ")
                    
                    //completion(json)
                    
                }else{
                    print("failed to JSON serialize")
                    //completion(nil)
                }
                
            }catch let error as NSError {
                print("Failed to load: \(error.localizedDescription)")
                //completion(nil)
            }
            
        }
        MKProgress.hide(true)
    }
    
    
    
}

    JSON string = {"author":"urn:li:person:vL0trBPoaA","specificContent":{"com.linkedin.ugc.ShareContent":{"shareCommentary":{"text":"Hello World! Share through LinkedIn SDK"},"shareMediaCategory":"NONE"}},"visibility":{"com.linkedin.ugc.MemberNetworkVisibility":"PUBLIC"},"lifecycleState":"PUBLISHED"}
Parameters == ["author": "urn:li:person:vL0trBPoaA", "specificContent": {
    "com.linkedin.ugc.ShareContent" =     {
        shareCommentary =         {
            text = "Hello World! Share through LinkedIn SDK";
        };
        shareMediaCategory = NONE;
    };
}, "visibility": {
    "com.linkedin.ugc.MemberNetworkVisibility" = PUBLIC;
}, "lifecycleState": "PUBLISHED"]

JSON RESPONSE ====>>>> ["serviceErrorCode": 100, "status": 403, "message": Not enough permissions to access: POST /ugcPosts] 

虽然我启用了权限。在此处输入图像描述

任何帮助,将不胜感激。

标签: swift5linkedin-api

解决方案


推荐阅读