Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ShareContext don't post and dont have error too #131

Closed
saroar opened this issue May 29, 2018 · 20 comments
Closed

ShareContext don't post and dont have error too #131

saroar opened this issue May 29, 2018 · 20 comments
Assignees

Comments

@saroar
Copy link

saroar commented May 29, 2018

Description

Describe the issue in detail here

i am trying to share from my ios app here is my code

no error from this

guard let pic = PerfectLocalAuth.userdetails["picture"] as? String else {
            return
        }
        
        if let url = URL(string: pic) {
            let task = URLSession.shared.dataTask(with: url, completionHandler: { data, response, error in
                if let data = data {
                    VK.sessions.default.share(
                        ShareContext(
                            text: "This post made with #SwiftyVK 🖖🏽",
                            images: [
                                ShareImage(data: data, type: .jpg)
                            ],
                            link: ShareLink(
                                title: "Follow the white rabbit", // Link description
                                url: URL(string: "localhost")! // URL to site
                            )
                        ),
                        onSuccess: { response in
                            print(response)
                    },
                        onError: { error in
                            print(error)
                    })
                }
            })
            task.resume()
}

here is my func

func postToFeedForVK() {
        VK.API.Users.get([
            .filters: "post",
            .returnBanned: "0",
            .fields: "first_name,last_name,photo_50,gid,name,photo"
            ])
            .onSuccess {

                do {
                    let response = try JSONSerialization.jsonObject(with: $0)
                    print(response)

                } catch {
                    print(error)
                }
            }.send()
        } < this func working that mean i have token and session 

i have already Oauth2 install so I get this
so do this

/* ==========================================================
     VK
     ========================================================== */
    @IBAction func doVkOAuth(_ sender: Any) {
        let service = "Vk"
        
        guard var parameters = services[service] else {
            print("\(service) not configured")
            return
        }
        
        let oauthswift = OAuth2Swift(
            consumerKey:    parameters["consumerKey"] ?? "",
            consumerSecret: parameters["consumerSecret"] ?? "",
            authorizeUrl:   "https://oauth.vk.com/authorize",
            accessTokenUrl: "https://oauth.vk.com/access_token",
            responseType:   "code"
        )
        
        self.oauthswift = oauthswift
        oauthswift.authorizeURLHandler = getURLHandler()
        let state = generateState(withLength: 20)
        _ = oauthswift.authorize(
            withCallbackURL: URL(string: "\(PerfectLocalAuth.host)/api/v1/oauth/return/vk")!,
            scope: "profile, city, photos, email, friends",
            state: state,
            success: { credential, response, parameters in
                print("credential.oauthToken", credential.oauthToken)
                
                // send upgrade user signal to Perfect OAuth2 Server
                let accessToken = credential.oauthToken
                
                do {
                    try VK.sessions.default.logIn(rawToken: accessToken, expires: TimeInterval(0)) *******
                } catch {
                    print("VK.sessions.default.logIn rawToken error")
                }

Environment

Key Value
Platform e.g. ios
Platform version 11.3
Xcode version exact version e.g. 9.3.1
Swift version exact version e.g. 4.1
SwiftyVK version exact version3.1.5
Integration Method cocoapods

Checklist

Check all points of list below and set [x] on each checked point:

  • [x ] I have looked and not find decision at README.md
  • [x ] I have looked and reproduce this behaviour in Example project
  • [ x] I have not find duplicates of this issue in issues list
  • [x ] I made an understandable short title and exhaustive description
  • [x ] I attach stack traces or errors description
  • [ x] I completely describe the environment
  • [x ] I have full filled out this issue template
@saroar
Copy link
Author

saroar commented May 29, 2018

how i am trying something like this

guard
            let pathToImage = Bundle.main.path(forResource: "278", ofType: "png"),
            let data = try? Data(contentsOf: URL(fileURLWithPath: pathToImage)),
            let link = URL(string: "https://en.wikipedia.org/wiki/Hyperspace")
            else {
                print("Can not find testImage.png")
                return
        }
        
        VK.sessions.default.share(
            ShareContext(
                text: "This post made with #SwiftyVK 🖖🏽",
                images: [
                    ShareImage(data: data, type: .jpg),
                    ShareImage(data: data, type: .jpg)
                ],
                link: ShareLink(
                    title: "Follow the white rabbit",
                    url: link
                )
            ),
            onSuccess: { print("SwiftyVK: successfully shared with \n \(JSON($0))") },
            onError: { print("SwiftyVK: share failed with \n \($0)") }
        )

error is

image not uploaded with error: jsonNotParsed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})

image not uploaded with error: jsonNotParsed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})

@saroar
Copy link
Author

saroar commented May 29, 2018

also getting an error when trying to upload photos

    func postToFeedForVK() {
        guard
            let pathToImage = Bundle.main.path(forResource: "matroshka", ofType: "png"),
            let data = try? Data(contentsOf: URL(fileURLWithPath: pathToImage))
            else {
                print("Can not find testImage.png")
                return
        }
        
        let media = Media.image(data: data, type: .png)
        
        VK.API.Upload.Photo.toWall(media, to: .user(id: "\(PerfectLocalAuth.vkUserId)"))
            .onSuccess { print("SwiftyVK: upload successed with \n \(JSON($0))") }
            .onError { print("SwiftyVK: upload failed with \n \($0)")}
            .onProgress { print($0) }
            .send()
}

@west0r
Copy link
Member

west0r commented May 29, 2018

Hello. Thanks for using SwiftyVK.

I read your comments but issue looks strange and I can't reproduce it. Please make following steps:

  1. Try to share post or photo from example application in this repository. (You need change App id and bundle id in example to yours) What's the result? I am getting valid success response.

  2. Be sure that PerfectLocalAuth.vkUserId or other strings are not optional because optional strings in construction like "\(PerfectLocalAuth.vkUserId)" can be Optional(1234567890) and this is not valid data for request.

  3. Try to set breakpoint in Response.swift line 9 and print string from rawData or sniff traffic with any traffic sniffer (for example Charles).

@saroar
Copy link
Author

saroar commented May 29, 2018

  1. Yes I change everything as you see I can get USER from this func
            .filters: "post",
            .returnBanned: "0",
            .fields: "first_name,last_name,photo_50,gid,name,photo"
            ])
            .onSuccess {

                do {
                    let response = try JSONSerialization.jsonObject(with: $0)
                    print(response)

                } catch {
                    print(error)
                }
            }.send()
        }```
2. let me try 

3. which number 9 oo sorry i don't use ur example code 

4. 
```func vkNeedToPresent(viewController: VKViewController) {
        if let rootVC = UIApplication.shared.keyWindow?.rootViewController {
            rootVC.present(viewController, animated: true)
        }
    }``` how i can change this from rootViewController to TabViewController 

5. i am already use Oauth2 to here i login 

/* ==========================================================
VK
========================================================== */
@IBAction func doVkOAuth(_ sender: Any) {
let service = "Vk"

    guard var parameters = services[service] else {
        print("\(service) not configured")
        return
    }
    
    let oauthswift = OAuth2Swift(
        consumerKey:    parameters["consumerKey"] ?? "",
        consumerSecret: parameters["consumerSecret"] ?? "",
        authorizeUrl:   "https://oauth.vk.com/authorize",
        accessTokenUrl: "https://oauth.vk.com/access_token",
        responseType:   "code"
    )
    
    self.oauthswift = oauthswift
    oauthswift.authorizeURLHandler = getURLHandler()
    let state = generateState(withLength: 20)
    _ = oauthswift.authorize(
        withCallbackURL: URL(string: "\(PerfectLocalAuth.host)/api/v1/oauth/return/vk")!,
        scope: "profile, city, photos, email, friends, wall",
        state: state,
        success: { credential, response, parameters in
            print("credential.oauthToken", credential.oauthToken)
            
            // send upgrade user signal to Perfect OAuth2 Server
            let accessToken = credential.oauthToken
            
            do {
                try VK.sessions.default.logIn(rawToken: accessToken, expires: TimeInterval(0))
            } catch {
                print("VK.sessions.default.logIn rawToken error")
            }
            
            PerfectLocalAuth.upgradeUser("vk", accessToken, { userid in
                
                PerfectLocalAuth.userid = userid
                PerfectLocalAuth.accountType = "vk"
                
                let token = KeychainSwift()
                
                let updateProfilePicUrl = "\(PerfectLocalAuth.host)/api/v1/updateProfileAvator/\(userid)"
                
                self.getProfileVk(oauthswift, accessToken: accessToken, success: { data in

                    let response =  data["response"][0]
                    
                    print("VK data after login", response)
                    
                    let picUrl   = response["photo_400_orig"].stringValue
                    let location = response["city"]["title"].stringValue
                    let params   = ["picture": picUrl, "location": location] as [String: Any]
                    PerfectLocalAuth.vkUserId = response["id"].int!
                    
                    NetworkignService.shared.postRequest(params: params, route: updateProfilePicUrl, completion: { _ in})
                    
                    PerfectLocalAuth.userdetails["location"] = location
                    PerfectLocalAuth.userdetails["picture"] = picUrl
                    
                    token.set(accessToken, forKey: picUrl + "vk")

                    DispatchQueue.main.async {
                        self.performSegue(withIdentifier: "welcome", sender: self)
                    }
                })

// self.getFriendsProfileFacebook(oauthswift, success: { })
})

    }, failure: { error in
        print("VK login fail:", error.localizedDescription, terminator: "")
    })
}
sorry i knwo this code can be improve with Codable but i will do later 

@west0r
Copy link
Member

west0r commented May 29, 2018

Please use example app and try to reproduce this error in it. Do not copy code from example to your app, just use example.

Response.swift line 9 in SwiftyVK library, not example app.

What for you use OAuth2Swift? SwiftyVK contains its own authorization logic.

Please do not write lot of code because it's hard to understand without all context.

@saroar
Copy link
Author

saroar commented May 29, 2018

OAuth2Swift i use with my server i get everything from server server talk with VK
my server also written swift so i was trying to use SwiftyVK for post or share and for login OAuth2Swift

can i use OAuth2Swift token with SwiftyVK?
what i mean by when get token from my server i save into

do {
                    try VK.sessions.default.logIn(rawToken: `accessToken`, expires: TimeInterval(0))
                } catch {
                    print("VK.sessions.default.logIn rawToken error")
                }

this one i am recieving accessToken when i login by OAuth2Swift

may be i can solve it but i need to knwo how i can change from rootViewController to TabBarController

        if let rootVC = UIApplication.shared.keyWindow?.rootViewController {
            rootVC.present(viewController, animated: true)
        }
    }```


@saroar
Copy link
Author

saroar commented May 29, 2018

mine one it not rootViewController
so i need to figure out how i can do with

class TabBarC: UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad(); printTypeOf(self)
    }
}

@west0r
Copy link
Member

west0r commented May 29, 2018

If you write mobile VK application, you should use auth for Standalone-app, not web-site, because token which was received on server can be not valid on device because they are have different IP addresses. Maybe you can use token from your server but I and VK documentation don't recommend it.

To show WebView from SwiftyVK you should show it from topViewController instead of rootViewController. Maybe this link can help you to find topViewController - https://stackoverflow.com/questions/26667009/get-top-most-uiviewcontroller

@saroar
Copy link
Author

saroar commented May 29, 2018

Thanks, I think I solve it with not server token

@saroar saroar closed this as completed May 29, 2018
@saroar
Copy link
Author

saroar commented May 29, 2018

You Done Great JOb МОЛОДЕЦ

@west0r west0r self-assigned this May 29, 2018
@saroar
Copy link
Author

saroar commented May 29, 2018

one last quis can i share also in facebook same post

        guard #available(iOS 8.0, macOS 10.11, *) else {
            print("Sharing available only on iOS 8.0+ and macOS 10.11+")
            return
        }

        guard
            let pic = PerfectLocalAuth.userdetails["picture"] as? String,
            let url = URL(string: pic)

            else {
                print("Image link missing")
                return
        }

        let task = URLSession.shared.dataTask(with: url, completionHandler: { data, response, error in

            guard
                let data = data,
                let link = URL(string: "https://en.wikipedia.org/wiki/Hyperspace")
                else {
                    print("Can not find testImage.png")
                    return
            }

            VK.sessions.default.share(
                ShareContext(
                    text: "This post made with #SwiftyVK 🖖🏽",
                    images: [
                        ShareImage(data: data, type: .png),
                        ShareImage(data: data, type: .png)
                    ],
                    link: ShareLink(
                        title: "Follow the white rabbit",
                        url: url
                    )
                ),
                onSuccess: { print("SwiftyVK: successfully shared with \n \(JSON($0))") },
                onError: { print("SwiftyVK: share failed with \n \($0)") }
            )

        })
        task.resume()

i like to knwo becz i see this code

struct ShareContextPreferencesSet {
    let twitter: Bool
    let facebook: Bool
    let livejournal: Bool
}

@west0r
Copy link
Member

west0r commented May 29, 2018

It decided only by user in post preferences UI because user can doesn't link own facebook profile to VK or want to share post to other social networks.

@saroar
Copy link
Author

saroar commented May 29, 2018

i want to share same post to other social networks
is it possible?

@saroar
Copy link
Author

saroar commented May 29, 2018

can I also delete this post
i should to delete from my app after 4 hours its even for 4 hours only
how i can do it
http://prntscr.com/jo6cvd
its working now

@west0r
Copy link
Member

west0r commented May 29, 2018

SwiftyVK doesn't provide ability to share posts to other social networks because it's library only for VK. But VK does if user link own Facebook/Twitter account to VK in site preferences and allows sharing. Only user can decide when and what share to other networks, you can't.

@saroar
Copy link
Author

saroar commented May 29, 2018

can I also delete this post
i should to delete from my iOS app after 4 hours its even for 4 hours only
how i can do it

@west0r
Copy link
Member

west0r commented May 30, 2018

You can save post info after sharing and delete this post lately with https://vk.com/dev/wall.delete method.

@saroar
Copy link
Author

saroar commented May 30, 2018

Hi did you check your real iPhone i found some bug i create one video from my iPhone but how I can share with you

@saroar
Copy link
Author

saroar commented May 31, 2018

when i try to with real device and click share button it goes to open my iPhone app then ask me permission after i get permission from iPhone vk app it doesn't redirect to my app this is 1a st problem
2nd when i go back my original app it shows me login screen then i have to login and share my post

why its open VK app if my own app login screen?
please try your self in your own iPhone and let me know thanks

@saroar saroar reopened this May 31, 2018
@west0r
Copy link
Member

west0r commented May 31, 2018

Please read carefully this README section and set all schemes and bundle id right

@saroar saroar closed this as completed Jun 1, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants