Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在swift中将图像/视频发布到twitter_Ios_Swift_Twitter - Fatal编程技术网

Ios 在swift中将图像/视频发布到twitter

Ios 在swift中将图像/视频发布到twitter,ios,swift,twitter,Ios,Swift,Twitter,我正在使用TwitterKit,我需要发布一个带有图像或视频以及描述的状态。问题是它没有给我任何类型的错误代码,所以我不知道为什么它不工作。以下是我目前掌握的代码: 编辑:好的,现在我打印出一个错误。错误是 Error uploading image Optional(Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x14604e90 {NSErrorFailingURLStringKey=h

我正在使用TwitterKit,我需要发布一个带有图像或视频以及描述的状态。问题是它没有给我任何类型的错误代码,所以我不知道为什么它不工作。以下是我目前掌握的代码:

编辑:好的,现在我打印出一个错误。错误是

Error uploading image Optional(Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x14604e90 {NSErrorFailingURLStringKey=https://upload.twitter.com/1.1/media/upload.json, NSErrorFailingURLKey=https://upload.twitter.com/1.1/media/upload.json, NSLocalizedDescription=The request timed out., NSUnderlyingError=0x14611520 "The request timed out."})
编辑2:好的,下面所有的代码都正常工作,除了当我试图上传一个视频时,它会发回400个错误错误请求

所以一切都是一样的,除了我更改了以下代码的媒体行:

var imageData : NSData = UIImageJPEGRepresentation(self.image!, 0.5)
                parameters["media"] = imageData.base64EncodedStringWithOptions(nil)
对此

parameters["media"] = self.video!.base64EncodedStringWithOptions(nil) //self.video is NSData
这是代码:

 Twitter.sharedInstance().logInWithCompletion {
                    (session, error) -> Void in
                    if session != nil {
                        println("signed in as \(session.userName)")
                        let strUploadUrl = "https://upload.twitter.com/1.1/media/upload.json"
                        let strStatusUrl = "https://api.twitter.com/1.1/statuses/update.json"
                        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
                        var twAPIClient = Twitter.sharedInstance().APIClient
                        var error: NSError?
                        var parameters:Dictionary = Dictionary<String, String>()
                        // get image from bundle
                        var imageData : NSData = UIImagePNGRepresentation(self.image!)

                        parameters["media"] = imageData.base64EncodedStringWithOptions(nil)
    //for uploading video would I just do this parameters["media'] = NSData.dataWithContentsOfMappedFile(url.relativePath!) as? NSData
                        var twUploadRequest = twAPIClient.URLRequestWithMethod("POST", URL: strUploadUrl, parameters: parameters, error: &error)
                        if true {
                            twAPIClient.sendTwitterRequest(twUploadRequest) {
                                (uploadResponse, uploadResultData, uploadConnectionError) -> Void in
                                if (uploadConnectionError == nil) {
                                    // using SwiftyJSON to parse result
                                    let json = JSON(data: uploadResultData!)
                                    // check for media id in result
                                    if (json["media_id_string"].string != nil) {
                                        println("result = \(json)")
                                        // post a status with link to media
                                        parameters = Dictionary<String, String>()
                                        parameters["status"] = "Hey look at this"
                                        parameters["media_ids"] = json["media_id_string"].string!
                                        var twStatusRequest = twAPIClient.URLRequestWithMethod("POST", URL: strStatusUrl, parameters: parameters, error: &error)
                                        if true //(twStatusRequest != nil)
                                        {
                                            twAPIClient.sendTwitterRequest(twStatusRequest) { (statusResponse, statusData, statusConnectionError) -> Void in
                                                if (statusConnectionError != nil) {
                                                    println("Error posting status \(statusConnectionError)")
                                                }
                                            } // completion
                                        } else {
                                            println("Error creating status request \(error)")
                                        }
                                    } else {
                                        println("Media_id not found in result = \(json)")
                                    }
                                } else {
                                    println("Error uploading image \(uploadConnectionError)")
                                }
                            } // completion
                        } else {
                            println("Error creating upload request \(error)")
                        }
                        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                    }
                }
Twitter.sharedInstance().logInWithCompletion{
(会话,错误)->在中无效
如果会话!=nil{
println(“以\(session.userName)身份登录”)
让strUploadUrl=”https://upload.twitter.com/1.1/media/upload.json"
让strStatusUrl=”https://api.twitter.com/1.1/statuses/update.json"
UIApplication.sharedApplication().networkActivityIndicatorVisible=true
var twAPIClient=Twitter.sharedInstance().APIClient
var错误:N错误?
变量参数:Dictionary=Dictionary()
//从包中获取图像
var-imageData:NSData=UIImagePNGRepresentation(self.image!)
参数[“媒体”]=imageData.base64EncodedStringWithOptions(无)
//对于上传视频,我只需将参数[“媒体”]=NSData.dataWithContentsOfMappedFile(url.relativePath!)作为?NSData执行即可
var twUploadRequest=twAPIClient.URLRequestWithMethod(“POST”,URL:strUploadUrl,参数:参数,错误:&error)
如果是真的{
twAPIClient.sendTwitterRequest(twUploadRequest){
(uploadResponse、uploadResultData、uploadConnectionError)->中的Void
如果(uploadConnectionError==nil){
//使用SwiftyJSON解析结果
让json=json(数据:uploadResultData!)
//检查结果中的媒体id
如果(json[“媒体id字符串”].string!=nil){
println(“结果=\(json)”)
//发布带有媒体链接的状态
参数=字典()
参数[“状态”]=“嘿,看看这个”
参数[“媒体id”]=json[“媒体id\U字符串”]。字符串!
var twStatusRequest=twAPIClient.URLRequestWithMethod(“POST”,URL:strStatusUrl,参数:参数,错误:&error)
如果为true/(twStatusRequest!=nil)
{
twAPIClient.sendTwitterRequest(TwaStatusRequest){(statusResponse,statusData,statusConnectionError)->在中无效
如果(statusConnectionError!=无){
println(“错误发布状态\(statusConnectionError)”)
}
}//完成
}否则{
println(“创建状态请求时出错\(错误)”)
}
}否则{
println(“在结果=\(json)中找不到媒体id”)
}
}否则{
println(“上传图像时出错\(uploadConnectionError)”)
}
}//完成
}否则{
println(“创建上载请求时出错\(错误)”)
}
UIApplication.sharedApplication().networkActivityIndicatorVisible=false
}
}

最新的推特API使在推特上发布带有图像和消息的推特变得非常容易。下面是基于您上面的示例的示例代码。如果您遇到任何问题,请验证并让我知道。更多详细信息,请访问->


注意:
println(“错误创建上传请求\(错误)”)
将永远不会执行,因为您正在询问
是否为true
,这始终为true。与
println(“错误创建状态请求\(错误)”相同)
。此外,您肯定应该阅读
statusResponse
中填充的内容,而不仅仅是检查错误,它可能会提供信息。好的,现在我得到一个错误,我想可能是图像格式错误或其他什么
TWTRTwitter.sharedInstance().logInWithCompletion {
                (session, error) -> Void in
                if session != nil {
                    println("signed in as \(session.userName)")

                    let twitterUserID = TWTRTwitter.sharedInstance().sessionStore.session()?.userIDUIApplication.sharedApplication().networkActivityIndicatorVisible = true
                    var twAPIClient = TWTRAPIClient(userID: twitterUserID)
                    twitterAPIclient.sendTweet(withText: "Hey look at this", image: self.image!, completion: {(tweet, error) in

        if tweet?.createdAt != nil {
            print("Tweet posted: \(tweet.debugDescription)")
        }
        if error?.localizedDescription != nil {
            print("error posting Tweet: \(error?.localizedDescription ?? "default error message")")
        }
    })     UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                }
            }