簡體   English   中英

如何將應用程序中的Linkedin SDK集成到使用Swift進行登錄和共享

[英]How to integrate Linkedin SDK in app to Login & share using Swift

我正在嘗試使用swift在iOS中集成LinkedIn SDK

我在Objective-C中找到了以下代碼

我是swift的新手,我試圖在swift中轉換這個代碼,但它不起作用。 Plz建議我如何在swift中轉換下面的代碼。 或者我如何整合Linkedin Sdk登錄並使用swift通過我的應用程序分享..

enter code here
[LISDKSessionManager createSessionWithAuth:permissions state:nil showGoToAppStoreDialog:YES successBlock:^(NSString *returnState){
 NSLog(@"%s","success called!");
 LISDKSession *session = [[LISDKSessionManager sharedInstance] session];
 NSLog(@"Session  : %@", session.description);

 [[LISDKAPIHelper sharedInstance] getRequest:@"https://api.linkedin.com/v1/people/~"
                                        success:^(LISDKAPIResponse *response) {

 NSData* data = [response.data dataUsingEncoding:NSUTF8StringEncoding];
 NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

 NSString *authUsername = [NSString stringWithFormat: @"%@ %@", [dictResponse valueForKey: @"firstName"], [dictResponse valueForKey: @"lastName"]];
 NSLog(@"Authenticated user name  : %@", authUsername);
 [self.lblAuthenticatedUser setText: authUsername];

  } error:^(LISDKAPIError *apiError) {
   NSLog(@"Error  : %@", apiError);
  }];
  } errorBlock:^(NSError *error) {
  NSLog(@"Error called  : %@", error);
 }];

這就是我設法通過LinkedIn驗證用戶的方法,使用SwiftyJSON庫來解析響應。 https://github.com/SwiftyJSON/SwiftyJSON截至2015年5月,LinkedIn限制訪問其API,只允許訪問基本配置文件字段/電子郵件。 您還需要在開發人員控制台中的應用程序下為r_basicprofile和r_emailaddress設置基本權限,以使其正常工作。

希望這可以幫助

@IBAction func connectWithLinkedIn(sender: AnyObject) {

  let url = NSString(string:"https://api.linkedin.com/v1/people/~:(id,industry,firstName,lastName,emailAddress,headline,summary,publicProfileUrl,specialties,positions:(id,title,summary,start-date,end-date,is-current,company:(id,name,type,size,industry,ticker)),pictureUrls::(original),location:(name))?format=json")

    let permissions: [AnyObject] = [LISDK_BASIC_PROFILE_PERMISSION, LISDK_EMAILADDRESS_PERMISSION]

    LISDKSessionManager.createSessionWithAuth(permissions, state: nil, showGoToAppStoreDialog: true, successBlock: { (success) -> () in
        if LISDKSessionManager.hasValidSession() {
            LISDKAPIHelper.sharedInstance().getRequest(url as String, success: {
                response in
                print(response)
                print("successfully signed in")

                dispatch_async(dispatch_get_main_queue(), { () -> () in

                    if let dataFromString = response.data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
                        let result = JSON(data: dataFromString)


                        LISDKSessionManager.clearSession()

                        //Do something with the response for example
                        var picURL: String!

                        for stringInArray in result["pictureUrls"]["values"]{

                            let value = stringInArray.1.stringValue
                            print(value)
                            picURL = value
                        }
                       print(result["pictureUrls"]["values"].arrayValue)
                       print(result["specialties"].stringValue)


                        }


                })

                }, error: {
                    error in

                    LISDKAPIHelper.sharedInstance().cancelCalls()
                    LISDKSessionManager.clearSession()

                    print(error.localizedDescription)
                    //Do something with the error
            })
        }


        print("success called!")


        }, errorBlock: { (error) -> () in
            print("%s", "error called!")

            LISDKAPIHelper.sharedInstance().cancelCalls()
            LISDKSessionManager.clearSession()
    })




}

你可以更喜歡這個片段用於LinkedIn共享:

將其粘貼到有效的會話條件LISDKSessionManager.hasValidSession()

Swift 3x

let url: String = "https://api.linkedin.com/v1/people/~/shares"

let payloadStr: String = "{\"comment\":\"YOUR_APP_LINK_OR_WHATEVER_YOU_WANT_TO_SHARE\",\"visibility\":{\"code\":\"anyone\"}}"

let payloadData = payloadStr.data(using: String.Encoding.utf8)


LISDKAPIHelper.sharedInstance().postRequest(url, body: payloadData, success: { (response) in

print(response!.data)

}, error: { (error) in

print(error as! Error)

let alert = UIAlertController(title: "Alert!", message: "aomething went wrong", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)

alert.addAction(action)
self.present(alert, animated: true, completion: nil)


})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM